From 08aa4418c30cfc18ccc69a0f0f9cb9e17be6c196 Mon Sep 17 00:00:00 2001 From: Pierre Schmitz Date: Mon, 12 Aug 2013 09:28:15 +0200 Subject: Update to MediaWiki 1.21.1 --- tests/phpunit/includes/ArticleTablesTest.php | 33 - tests/phpunit/includes/ArticleTest.php | 82 - tests/phpunit/includes/BlockTest.php | 230 --- tests/phpunit/includes/CdbTest.php | 84 - tests/phpunit/includes/DiffHistoryBlobTest.php | 40 - tests/phpunit/includes/EditPageTest.php | 40 - tests/phpunit/includes/ExternalStoreTest.php | 32 - tests/phpunit/includes/ExtraParserTest.php | 169 -- tests/phpunit/includes/FauxResponseTest.php | 70 - .../includes/FormOptionsInitializationTest.php | 85 - tests/phpunit/includes/FormOptionsTest.php | 90 - .../includes/GlobalFunctions/GlobalTest.php | 598 ------- .../includes/GlobalFunctions/GlobalWithDBTest.php | 29 - tests/phpunit/includes/GlobalFunctions/README | 2 - .../includes/GlobalFunctions/wfAssembleUrlTest.php | 111 -- .../includes/GlobalFunctions/wfBCP47Test.php | 133 -- .../includes/GlobalFunctions/wfBaseNameTest.php | 36 - .../includes/GlobalFunctions/wfExpandUrlTest.php | 80 - .../includes/GlobalFunctions/wfGetCallerTest.php | 35 - .../GlobalFunctions/wfRemoveDotSegmentsTest.php | 90 - .../GlobalFunctions/wfShorthandToIntegerTest.php | 28 - .../includes/GlobalFunctions/wfTimestampTest.php | 134 -- .../includes/GlobalFunctions/wfUrlencodeTest.php | 120 -- tests/phpunit/includes/HooksTest.php | 102 -- tests/phpunit/includes/HtmlTest.php | 580 ------ tests/phpunit/includes/HttpTest.php | 180 -- tests/phpunit/includes/IPTest.php | 542 ------ tests/phpunit/includes/JsonTest.php | 33 - tests/phpunit/includes/LanguageConverterTest.php | 130 -- tests/phpunit/includes/LicensesTest.php | 22 - tests/phpunit/includes/LinksUpdateTest.php | 154 -- tests/phpunit/includes/LocalFileTest.php | 108 -- tests/phpunit/includes/LocalisationCacheTest.php | 31 - tests/phpunit/includes/MWFunctionTest.php | 86 - tests/phpunit/includes/MWNamespaceTest.php | 628 ------- tests/phpunit/includes/MessageTest.php | 64 - tests/phpunit/includes/ParserOptionsTest.php | 35 - tests/phpunit/includes/PathRouterTest.php | 254 --- tests/phpunit/includes/PreferencesTest.php | 75 - tests/phpunit/includes/Providers.php | 44 - tests/phpunit/includes/RecentChangeTest.php | 273 --- tests/phpunit/includes/ResourceLoaderTest.php | 91 - tests/phpunit/includes/RevisionStorageTest.php | 408 ----- tests/phpunit/includes/RevisionTest.php | 125 -- tests/phpunit/includes/SampleTest.php | 98 - tests/phpunit/includes/SanitizerTest.php | 162 -- .../includes/SanitizerValidateEmailTest.php | 79 - .../phpunit/includes/SeleniumConfigurationTest.php | 228 --- tests/phpunit/includes/SiteConfigurationTest.php | 311 ---- tests/phpunit/includes/TemplateCategoriesTest.php | 36 - tests/phpunit/includes/TestUser.php | 58 - tests/phpunit/includes/TimeAdjustTest.php | 51 - tests/phpunit/includes/TimestampTest.php | 72 - tests/phpunit/includes/TitleMethodsTest.php | 201 --- tests/phpunit/includes/TitlePermissionTest.php | 660 ------- tests/phpunit/includes/TitleTest.php | 155 -- tests/phpunit/includes/UserTest.php | 171 -- tests/phpunit/includes/WebRequestTest.php | 216 --- tests/phpunit/includes/WikiPageTest.php | 784 -------- tests/phpunit/includes/XmlJsTest.php | 9 - tests/phpunit/includes/XmlSelectTest.php | 139 -- tests/phpunit/includes/XmlTest.php | 342 ---- tests/phpunit/includes/ZipDirectoryReaderTest.php | 79 - tests/phpunit/includes/api/ApiBlockTest.php | 117 -- tests/phpunit/includes/api/ApiEditPageTest.php | 84 - tests/phpunit/includes/api/ApiOptionsTest.php | 276 --- tests/phpunit/includes/api/ApiPurgeTest.php | 40 - tests/phpunit/includes/api/ApiQueryTest.php | 68 - tests/phpunit/includes/api/ApiTest.php | 280 --- tests/phpunit/includes/api/ApiTestCase.php | 187 -- tests/phpunit/includes/api/ApiTestCaseUpload.php | 148 -- tests/phpunit/includes/api/ApiUploadTest.php | 569 ------ tests/phpunit/includes/api/ApiWatchTest.php | 176 -- .../phpunit/includes/api/PrefixUniquenessTest.php | 24 - .../phpunit/includes/api/RandomImageGenerator.php | 463 ----- .../includes/api/format/ApiFormatPhpTest.php | 19 - .../includes/api/format/ApiFormatTestBase.php | 22 - .../phpunit/includes/api/generateRandomImages.php | 51 - tests/phpunit/includes/api/words.txt | 1000 ----------- tests/phpunit/includes/cache/GenderCacheTest.php | 101 -- .../phpunit/includes/cache/ProcessCacheLRUTest.php | 239 --- tests/phpunit/includes/db/DatabaseSQLTest.php | 147 -- tests/phpunit/includes/db/DatabaseSqliteTest.php | 326 ---- tests/phpunit/includes/db/DatabaseTest.php | 215 --- tests/phpunit/includes/db/ORMRowTest.php | 234 --- tests/phpunit/includes/db/TestORMRowTest.php | 174 -- tests/phpunit/includes/debug/MWDebugTest.php | 68 - .../phpunit/includes/filerepo/FileBackendTest.php | 1868 -------------------- tests/phpunit/includes/filerepo/FileRepoTest.php | 45 - tests/phpunit/includes/filerepo/StoreBatchTest.php | 123 -- .../includes/installer/InstallDocFormatterTest.php | 64 - tests/phpunit/includes/json/ServicesJsonTest.php | 93 - tests/phpunit/includes/libs/CSSJanusTest.php | 560 ------ tests/phpunit/includes/libs/CSSMinTest.php | 142 -- .../includes/libs/GenericArrayObjectTest.php | 245 --- tests/phpunit/includes/libs/IEUrlExtensionTest.php | 118 -- .../includes/libs/JavaScriptMinifierTest.php | 170 -- .../includes/media/BitmapMetadataHandlerTest.php | 146 -- tests/phpunit/includes/media/BitmapScalingTest.php | 151 -- tests/phpunit/includes/media/ExifBitmapTest.php | 100 -- tests/phpunit/includes/media/ExifRotationTest.php | 260 --- tests/phpunit/includes/media/ExifTest.php | 48 - .../phpunit/includes/media/FormatMetadataTest.php | 52 - .../includes/media/GIFMetadataExtractorTest.php | 96 - tests/phpunit/includes/media/GIFTest.php | 98 - tests/phpunit/includes/media/IPTCTest.php | 55 - .../includes/media/JpegMetadataExtractorTest.php | 94 - tests/phpunit/includes/media/JpegTest.php | 31 - tests/phpunit/includes/media/MediaHandlerTest.php | 50 - .../includes/media/PNGMetadataExtractorTest.php | 141 -- tests/phpunit/includes/media/PNGTest.php | 100 -- .../includes/media/SVGMetadataExtractorTest.php | 108 -- tests/phpunit/includes/media/TiffTest.php | 35 - tests/phpunit/includes/media/XMPTest.php | 158 -- tests/phpunit/includes/media/XMPValidateTest.php | 47 - .../includes/mobile/DeviceDetectionTest.php | 40 - tests/phpunit/includes/normal/CleanUpTest.php | 382 ---- .../phpunit/includes/parser/MagicVariableTest.php | 201 --- .../includes/parser/MediaWikiParserTest.php | 36 - tests/phpunit/includes/parser/NewParserTest.php | 895 ---------- .../phpunit/includes/parser/ParserMethodsTest.php | 33 - .../phpunit/includes/parser/ParserPreloadTest.php | 67 - tests/phpunit/includes/parser/PreprocessorTest.php | 233 --- tests/phpunit/includes/parser/TagHooksTest.php | 77 - tests/phpunit/includes/search/SearchEngineTest.php | 163 -- tests/phpunit/includes/search/SearchUpdateTest.php | 90 - .../includes/specials/QueryAllSpecialPagesTest.php | 79 - .../includes/specials/SpecialRecentchangesTest.php | 132 -- .../includes/specials/SpecialSearchTest.php | 116 -- .../phpunit/includes/upload/UploadFromUrlTest.php | 351 ---- tests/phpunit/includes/upload/UploadStashTest.php | 77 - tests/phpunit/includes/upload/UploadTest.php | 141 -- 132 files changed, 23506 deletions(-) delete mode 100644 tests/phpunit/includes/ArticleTablesTest.php delete mode 100644 tests/phpunit/includes/ArticleTest.php delete mode 100644 tests/phpunit/includes/BlockTest.php delete mode 100644 tests/phpunit/includes/CdbTest.php delete mode 100644 tests/phpunit/includes/DiffHistoryBlobTest.php delete mode 100644 tests/phpunit/includes/EditPageTest.php delete mode 100644 tests/phpunit/includes/ExternalStoreTest.php delete mode 100644 tests/phpunit/includes/ExtraParserTest.php delete mode 100644 tests/phpunit/includes/FauxResponseTest.php delete mode 100644 tests/phpunit/includes/FormOptionsInitializationTest.php delete mode 100644 tests/phpunit/includes/FormOptionsTest.php delete mode 100644 tests/phpunit/includes/GlobalFunctions/GlobalTest.php delete mode 100644 tests/phpunit/includes/GlobalFunctions/GlobalWithDBTest.php delete mode 100644 tests/phpunit/includes/GlobalFunctions/README delete mode 100644 tests/phpunit/includes/GlobalFunctions/wfAssembleUrlTest.php delete mode 100644 tests/phpunit/includes/GlobalFunctions/wfBCP47Test.php delete mode 100644 tests/phpunit/includes/GlobalFunctions/wfBaseNameTest.php delete mode 100644 tests/phpunit/includes/GlobalFunctions/wfExpandUrlTest.php delete mode 100644 tests/phpunit/includes/GlobalFunctions/wfGetCallerTest.php delete mode 100644 tests/phpunit/includes/GlobalFunctions/wfRemoveDotSegmentsTest.php delete mode 100644 tests/phpunit/includes/GlobalFunctions/wfShorthandToIntegerTest.php delete mode 100644 tests/phpunit/includes/GlobalFunctions/wfTimestampTest.php delete mode 100644 tests/phpunit/includes/GlobalFunctions/wfUrlencodeTest.php delete mode 100644 tests/phpunit/includes/HooksTest.php delete mode 100644 tests/phpunit/includes/HtmlTest.php delete mode 100644 tests/phpunit/includes/HttpTest.php delete mode 100644 tests/phpunit/includes/IPTest.php delete mode 100644 tests/phpunit/includes/JsonTest.php delete mode 100644 tests/phpunit/includes/LanguageConverterTest.php delete mode 100644 tests/phpunit/includes/LicensesTest.php delete mode 100644 tests/phpunit/includes/LinksUpdateTest.php delete mode 100644 tests/phpunit/includes/LocalFileTest.php delete mode 100644 tests/phpunit/includes/LocalisationCacheTest.php delete mode 100644 tests/phpunit/includes/MWFunctionTest.php delete mode 100644 tests/phpunit/includes/MWNamespaceTest.php delete mode 100644 tests/phpunit/includes/MessageTest.php delete mode 100644 tests/phpunit/includes/ParserOptionsTest.php delete mode 100644 tests/phpunit/includes/PathRouterTest.php delete mode 100644 tests/phpunit/includes/PreferencesTest.php delete mode 100644 tests/phpunit/includes/Providers.php delete mode 100644 tests/phpunit/includes/RecentChangeTest.php delete mode 100644 tests/phpunit/includes/ResourceLoaderTest.php delete mode 100644 tests/phpunit/includes/RevisionStorageTest.php delete mode 100644 tests/phpunit/includes/RevisionTest.php delete mode 100644 tests/phpunit/includes/SampleTest.php delete mode 100644 tests/phpunit/includes/SanitizerTest.php delete mode 100644 tests/phpunit/includes/SanitizerValidateEmailTest.php delete mode 100644 tests/phpunit/includes/SeleniumConfigurationTest.php delete mode 100644 tests/phpunit/includes/SiteConfigurationTest.php delete mode 100644 tests/phpunit/includes/TemplateCategoriesTest.php delete mode 100644 tests/phpunit/includes/TestUser.php delete mode 100644 tests/phpunit/includes/TimeAdjustTest.php delete mode 100644 tests/phpunit/includes/TimestampTest.php delete mode 100644 tests/phpunit/includes/TitleMethodsTest.php delete mode 100644 tests/phpunit/includes/TitlePermissionTest.php delete mode 100644 tests/phpunit/includes/TitleTest.php delete mode 100644 tests/phpunit/includes/UserTest.php delete mode 100644 tests/phpunit/includes/WebRequestTest.php delete mode 100644 tests/phpunit/includes/WikiPageTest.php delete mode 100644 tests/phpunit/includes/XmlJsTest.php delete mode 100644 tests/phpunit/includes/XmlSelectTest.php delete mode 100644 tests/phpunit/includes/XmlTest.php delete mode 100644 tests/phpunit/includes/ZipDirectoryReaderTest.php delete mode 100644 tests/phpunit/includes/api/ApiBlockTest.php delete mode 100644 tests/phpunit/includes/api/ApiEditPageTest.php delete mode 100644 tests/phpunit/includes/api/ApiOptionsTest.php delete mode 100644 tests/phpunit/includes/api/ApiPurgeTest.php delete mode 100644 tests/phpunit/includes/api/ApiQueryTest.php delete mode 100644 tests/phpunit/includes/api/ApiTest.php delete mode 100644 tests/phpunit/includes/api/ApiTestCase.php delete mode 100644 tests/phpunit/includes/api/ApiTestCaseUpload.php delete mode 100644 tests/phpunit/includes/api/ApiUploadTest.php delete mode 100644 tests/phpunit/includes/api/ApiWatchTest.php delete mode 100644 tests/phpunit/includes/api/PrefixUniquenessTest.php delete mode 100644 tests/phpunit/includes/api/RandomImageGenerator.php delete mode 100644 tests/phpunit/includes/api/format/ApiFormatPhpTest.php delete mode 100644 tests/phpunit/includes/api/format/ApiFormatTestBase.php delete mode 100644 tests/phpunit/includes/api/generateRandomImages.php delete mode 100644 tests/phpunit/includes/api/words.txt delete mode 100644 tests/phpunit/includes/cache/GenderCacheTest.php delete mode 100644 tests/phpunit/includes/cache/ProcessCacheLRUTest.php delete mode 100644 tests/phpunit/includes/db/DatabaseSQLTest.php delete mode 100644 tests/phpunit/includes/db/DatabaseSqliteTest.php delete mode 100644 tests/phpunit/includes/db/DatabaseTest.php delete mode 100644 tests/phpunit/includes/db/ORMRowTest.php delete mode 100644 tests/phpunit/includes/db/TestORMRowTest.php delete mode 100644 tests/phpunit/includes/debug/MWDebugTest.php delete mode 100644 tests/phpunit/includes/filerepo/FileBackendTest.php delete mode 100644 tests/phpunit/includes/filerepo/FileRepoTest.php delete mode 100644 tests/phpunit/includes/filerepo/StoreBatchTest.php delete mode 100644 tests/phpunit/includes/installer/InstallDocFormatterTest.php delete mode 100644 tests/phpunit/includes/json/ServicesJsonTest.php delete mode 100644 tests/phpunit/includes/libs/CSSJanusTest.php delete mode 100644 tests/phpunit/includes/libs/CSSMinTest.php delete mode 100644 tests/phpunit/includes/libs/GenericArrayObjectTest.php delete mode 100644 tests/phpunit/includes/libs/IEUrlExtensionTest.php delete mode 100644 tests/phpunit/includes/libs/JavaScriptMinifierTest.php delete mode 100644 tests/phpunit/includes/media/BitmapMetadataHandlerTest.php delete mode 100644 tests/phpunit/includes/media/BitmapScalingTest.php delete mode 100644 tests/phpunit/includes/media/ExifBitmapTest.php delete mode 100644 tests/phpunit/includes/media/ExifRotationTest.php delete mode 100644 tests/phpunit/includes/media/ExifTest.php delete mode 100644 tests/phpunit/includes/media/FormatMetadataTest.php delete mode 100644 tests/phpunit/includes/media/GIFMetadataExtractorTest.php delete mode 100644 tests/phpunit/includes/media/GIFTest.php delete mode 100644 tests/phpunit/includes/media/IPTCTest.php delete mode 100644 tests/phpunit/includes/media/JpegMetadataExtractorTest.php delete mode 100644 tests/phpunit/includes/media/JpegTest.php delete mode 100644 tests/phpunit/includes/media/MediaHandlerTest.php delete mode 100644 tests/phpunit/includes/media/PNGMetadataExtractorTest.php delete mode 100644 tests/phpunit/includes/media/PNGTest.php delete mode 100644 tests/phpunit/includes/media/SVGMetadataExtractorTest.php delete mode 100644 tests/phpunit/includes/media/TiffTest.php delete mode 100644 tests/phpunit/includes/media/XMPTest.php delete mode 100644 tests/phpunit/includes/media/XMPValidateTest.php delete mode 100644 tests/phpunit/includes/mobile/DeviceDetectionTest.php delete mode 100644 tests/phpunit/includes/normal/CleanUpTest.php delete mode 100644 tests/phpunit/includes/parser/MagicVariableTest.php delete mode 100644 tests/phpunit/includes/parser/MediaWikiParserTest.php delete mode 100644 tests/phpunit/includes/parser/NewParserTest.php delete mode 100644 tests/phpunit/includes/parser/ParserMethodsTest.php delete mode 100644 tests/phpunit/includes/parser/ParserPreloadTest.php delete mode 100644 tests/phpunit/includes/parser/PreprocessorTest.php delete mode 100644 tests/phpunit/includes/parser/TagHooksTest.php delete mode 100644 tests/phpunit/includes/search/SearchEngineTest.php delete mode 100644 tests/phpunit/includes/search/SearchUpdateTest.php delete mode 100644 tests/phpunit/includes/specials/QueryAllSpecialPagesTest.php delete mode 100644 tests/phpunit/includes/specials/SpecialRecentchangesTest.php delete mode 100644 tests/phpunit/includes/specials/SpecialSearchTest.php delete mode 100644 tests/phpunit/includes/upload/UploadFromUrlTest.php delete mode 100644 tests/phpunit/includes/upload/UploadStashTest.php delete mode 100644 tests/phpunit/includes/upload/UploadTest.php (limited to 'tests/phpunit/includes') diff --git a/tests/phpunit/includes/ArticleTablesTest.php b/tests/phpunit/includes/ArticleTablesTest.php deleted file mode 100644 index 17cee6e8..00000000 --- a/tests/phpunit/includes/ArticleTablesTest.php +++ /dev/null @@ -1,33 +0,0 @@ -mRights = array( 'createpage', 'edit', 'purge' ); - $wgLanguageCode = 'es'; - $wgContLang = Language::factory( 'es' ); - - $wgLang = Language::factory( 'fr' ); - $status = $page->doEdit( '{{:{{int:history}}}}', 'Test code for bug 14404', 0, false, $user ); - $templates1 = $title->getTemplateLinksFrom(); - - $wgLang = Language::factory( 'de' ); - $page->mPreparedEdit = false; // In order to force the rerendering of the same wikitext - - // We need an edit, a purge is not enough to regenerate the tables - $status = $page->doEdit( '{{:{{int:history}}}}', 'Test code for bug 14404', EDIT_UPDATE, false, $user ); - $templates2 = $title->getTemplateLinksFrom(); - - $this->assertEquals( $templates1, $templates2 ); - $this->assertEquals( $templates1[0]->getFullText(), 'Historial' ); - } - -} diff --git a/tests/phpunit/includes/ArticleTest.php b/tests/phpunit/includes/ArticleTest.php deleted file mode 100644 index 846d2b86..00000000 --- a/tests/phpunit/includes/ArticleTest.php +++ /dev/null @@ -1,82 +0,0 @@ -title = Title::makeTitle( NS_MAIN, 'SomePage' ); - $this->article = new Article( $this->title ); - - } - - /** cleanup title object and its article object */ - function tearDown() { - $this->title = null; - $this->article = null; - - } - - function testImplementsGetMagic() { - $this->assertEquals( false, $this->article->mLatest, "Article __get magic" ); - } - - /** - * @depends testImplementsGetMagic - */ - function testImplementsSetMagic() { - $this->article->mLatest = 2; - $this->assertEquals( 2, $this->article->mLatest, "Article __set magic" ); - } - - /** - * @depends testImplementsSetMagic - */ - function testImplementsCallMagic() { - $this->article->mLatest = 33; - $this->article->mDataLoaded = true; - $this->assertEquals( 33, $this->article->getLatest(), "Article __call magic" ); - } - - function testGetOrSetOnNewProperty() { - $this->article->ext_someNewProperty = 12; - $this->assertEquals( 12, $this->article->ext_someNewProperty, - "Article get/set magic on new field" ); - - $this->article->ext_someNewProperty = -8; - $this->assertEquals( -8, $this->article->ext_someNewProperty, - "Article get/set magic on update to new field" ); - } - - /** - * Checks for the existence of the backwards compatibility static functions (forwarders to WikiPage class) - */ - function testStaticFunctions() { - $this->assertEquals( WikiPage::selectFields(), Article::selectFields(), - "Article static functions" ); - $this->assertEquals( true, is_callable( "Article::onArticleCreate" ), - "Article static functions" ); - $this->assertEquals( true, is_callable( "Article::onArticleDelete" ), - "Article static functions" ); - $this->assertEquals( true, is_callable( "ImagePage::onArticleEdit" ), - "Article static functions" ); - $this->assertTrue( is_string( CategoryPage::getAutosummary( '', '', 0 ) ), - "Article static functions" ); - } - - function testWikiPageFactory() { - $title = Title::makeTitle( NS_FILE, 'Someimage.png' ); - $page = WikiPage::factory( $title ); - $this->assertEquals( 'WikiFilePage', get_class( $page ) ); - - $title = Title::makeTitle( NS_CATEGORY, 'SomeCategory' ); - $page = WikiPage::factory( $title ); - $this->assertEquals( 'WikiCategoryPage', get_class( $page ) ); - - $title = Title::makeTitle( NS_MAIN, 'SomePage' ); - $page = WikiPage::factory( $title ); - $this->assertEquals( 'WikiPage', get_class( $page ) ); - } -} diff --git a/tests/phpunit/includes/BlockTest.php b/tests/phpunit/includes/BlockTest.php deleted file mode 100644 index 0c95b8d1..00000000 --- a/tests/phpunit/includes/BlockTest.php +++ /dev/null @@ -1,230 +0,0 @@ -dumpBlocks(); - - $user = User::newFromName( 'UTBlockee' ); - if( $user->getID() == 0 ) { - $user->addToDatabase(); - $user->setPassword( 'UTBlockeePassword' ); - - $user->saveSettings(); - } - - // Delete the last round's block if it's still there - $oldBlock = Block::newFromTarget( 'UTBlockee' ); - if ( $oldBlock ) { - // An old block will prevent our new one from saving. - $oldBlock->delete(); - } - - $this->block = new Block( 'UTBlockee', $user->getID(), 0, - 'Parce que', 0, false, time() + 100500 - ); - $this->madeAt = wfTimestamp( TS_MW ); - - $this->block->insert(); - // save up ID for use in assertion. Since ID is an autoincrement, - // its value might change depending on the order the tests are run. - // ApiBlockTest insert its own blocks! - $newBlockId = $this->block->getId(); - if ($newBlockId) { - $this->blockId = $newBlockId; - } else { - throw new MWException( "Failed to insert block for BlockTest; old leftover block remaining?" ); - } - } - - /** - * debug function : dump the ipblocks table - */ - function dumpBlocks() { - $v = $this->db->query( 'SELECT * FROM unittest_ipblocks' ); - print "Got " . $v->numRows() . " rows. Full dump follow:\n"; - foreach( $v as $row ) { - print_r( $row ); - } - } - - function testInitializerFunctionsReturnCorrectBlock() { - // $this->dumpBlocks(); - - $this->assertTrue( $this->block->equals( Block::newFromTarget('UTBlockee') ), "newFromTarget() returns the same block as the one that was made"); - - $this->assertTrue( $this->block->equals( Block::newFromID( $this->blockId ) ), "newFromID() returns the same block as the one that was made"); - - } - - /** - * per bug 26425 - */ - function testBug26425BlockTimestampDefaultsToTime() { - // delta to stop one-off errors when things happen to go over a second mark. - $delta = abs( $this->madeAt - $this->block->mTimestamp ); - $this->assertLessThan( 2, $delta, "If no timestamp is specified, the block is recorded as time()"); - - } - - /** - * This is the method previously used to load block info in CheckUser etc - * passing an empty value (empty string, null, etc) as the ip parameter bypasses IP lookup checks. - * - * This stopped working with r84475 and friends: regression being fixed for bug 29116. - * - * @dataProvider dataBug29116 - */ - function testBug29116LoadWithEmptyIp( $vagueTarget ) { - $this->hideDeprecated( 'Block::load' ); - - $uid = User::idFromName( 'UTBlockee' ); - $this->assertTrue( ($uid > 0), 'Must be able to look up the target user during tests' ); - - $block = new Block(); - $ok = $block->load( $vagueTarget, $uid ); - $this->assertTrue( $ok, "Block->load() with empty IP and user ID '$uid' should return a block" ); - - $this->assertTrue( $this->block->equals( $block ), "Block->load() returns the same block as the one that was made when given empty ip param " . var_export( $vagueTarget, true ) ); - } - - /** - * CheckUser since being changed to use Block::newFromTarget started failing - * because the new function didn't accept empty strings like Block::load() - * had. Regression bug 29116. - * - * @dataProvider dataBug29116 - */ - function testBug29116NewFromTargetWithEmptyIp( $vagueTarget ) { - $block = Block::newFromTarget('UTBlockee', $vagueTarget); - $this->assertTrue( $this->block->equals( $block ), "newFromTarget() returns the same block as the one that was made when given empty vagueTarget param " . var_export( $vagueTarget, true ) ); - } - - function dataBug29116() { - return array( - array( null ), - array( '' ), - array( false ) - ); - } - - function testBlockedUserCanNotCreateAccount() { - $username = 'BlockedUserToCreateAccountWith'; - $u = User::newFromName( $username ); - $u->setPassword( 'NotRandomPass' ); - $u->addToDatabase(); - unset( $u ); - - - // Sanity check - $this->assertNull( - Block::newFromTarget( $username ), - "$username should not be blocked" - ); - - // Reload user - $u = User::newFromName( $username ); - $this->assertFalse( - $u->isBlockedFromCreateAccount(), - "Our sandbox user should be able to create account before being blocked" - ); - - // Foreign perspective (blockee not on current wiki)... - $block = new Block( - /* $address */ $username, - /* $user */ 14146, - /* $by */ 0, - /* $reason */ 'crosswiki block...', - /* $timestamp */ wfTimestampNow(), - /* $auto */ false, - /* $expiry */ $this->db->getInfinity(), - /* anonOnly */ false, - /* $createAccount */ true, - /* $enableAutoblock */ true, - /* $hideName (ipb_deleted) */ true, - /* $blockEmail */ true, - /* $allowUsertalk */ false, - /* $byName */ 'MetaWikiUser' - ); - $block->insert(); - - // Reload block from DB - $userBlock = Block::newFromTarget( $username ); - $this->assertTrue( - (bool) $block->prevents( 'createaccount' ), - "Block object in DB should prevents 'createaccount'" - ); - - $this->assertInstanceOf( - 'Block', - $userBlock, - "'$username' block block object should be existent" - ); - - // Reload user - $u = User::newFromName( $username ); - $this->assertTrue( - (bool) $u->isBlockedFromCreateAccount(), - "Our sandbox user '$username' should NOT be able to create account" - ); - } - - function testCrappyCrossWikiBlocks() { - // Delete the last round's block if it's still there - $oldBlock = Block::newFromTarget( 'UserOnForeignWiki' ); - if ( $oldBlock ) { - // An old block will prevent our new one from saving. - $oldBlock->delete(); - } - - // Foreign perspective (blockee not on current wiki)... - $block = new Block( - /* $address */ 'UserOnForeignWiki', - /* $user */ 14146, - /* $by */ 0, - /* $reason */ 'crosswiki block...', - /* $timestamp */ wfTimestampNow(), - /* $auto */ false, - /* $expiry */ $this->db->getInfinity(), - /* anonOnly */ false, - /* $createAccount */ true, - /* $enableAutoblock */ true, - /* $hideName (ipb_deleted) */ true, - /* $blockEmail */ true, - /* $allowUsertalk */ false, - /* $byName */ 'MetaWikiUser' - ); - - $res = $block->insert( $this->db ); - $this->assertTrue( (bool)$res['id'], 'Block succeeded' ); - - // Local perspective (blockee on current wiki)... - $user = User::newFromName( 'UserOnForeignWiki' ); - $user->addToDatabase(); - // Set user ID to match the test value - $this->db->update( 'user', array( 'user_id' => 14146 ), array( 'user_id' => $user->getId() ) ); - $user = null; // clear - - $block = Block::newFromID( $res['id'] ); - $this->assertEquals( 'UserOnForeignWiki', $block->getTarget()->getName(), 'Correct blockee name' ); - $this->assertEquals( '14146', $block->getTarget()->getId(), 'Correct blockee id' ); - $this->assertEquals( 'MetaWikiUser', $block->getBlocker(), 'Correct blocker name' ); - $this->assertEquals( 'MetaWikiUser', $block->getByName(), 'Correct blocker name' ); - $this->assertEquals( 0, $block->getBy(), 'Correct blocker id' ); - } -} diff --git a/tests/phpunit/includes/CdbTest.php b/tests/phpunit/includes/CdbTest.php deleted file mode 100644 index b5418dd7..00000000 --- a/tests/phpunit/includes/CdbTest.php +++ /dev/null @@ -1,84 +0,0 @@ -markTestSkipped( 'Native CDB support is not available' ); - } - } - - public function testCdb() { - $dir = wfTempDir(); - if ( !is_writable( $dir ) ) { - $this->markTestSkipped( "Temp dir isn't writable" ); - } - - $w1 = new CdbWriter_PHP( "$dir/php.cdb" ); - $w2 = new CdbWriter_DBA( "$dir/dba.cdb" ); - - $data = array(); - for ( $i = 0; $i < 1000; $i++ ) { - $key = $this->randomString(); - $value = $this->randomString(); - $w1->set( $key, $value ); - $w2->set( $key, $value ); - - if ( !isset( $data[$key] ) ) { - $data[$key] = $value; - } - } - - $w1->close(); - $w2->close(); - - $this->assertEquals( - md5_file( "$dir/dba.cdb" ), - md5_file( "$dir/php.cdb" ), - 'same hash' - ); - - $r1 = new CdbReader_PHP( "$dir/php.cdb" ); - $r2 = new CdbReader_DBA( "$dir/dba.cdb" ); - - foreach ( $data as $key => $value ) { - if ( $key === '' ) { - // Known bug - continue; - } - $v1 = $r1->get( $key ); - $v2 = $r2->get( $key ); - - $v1 = $v1 === false ? '(not found)' : $v1; - $v2 = $v2 === false ? '(not found)' : $v2; - - # cdbAssert( 'Mismatch', $key, $v1, $v2 ); - $this->cdbAssert( "PHP error", $key, $v1, $value ); - $this->cdbAssert( "DBA error", $key, $v2, $value ); - } - - unlink( "$dir/dba.cdb" ); - unlink( "$dir/php.cdb" ); - } - - private function randomString() { - $len = mt_rand( 0, 10 ); - $s = ''; - for ( $j = 0; $j < $len; $j++ ) { - $s .= chr( mt_rand( 0, 255 ) ); - } - return $s; - } - - private function cdbAssert( $msg, $key, $v1, $v2 ) { - $this->assertEquals( - $v2, - $v1, - $msg . ', k=' . bin2hex( $key ) - ); - } -} diff --git a/tests/phpunit/includes/DiffHistoryBlobTest.php b/tests/phpunit/includes/DiffHistoryBlobTest.php deleted file mode 100644 index cdb6ed2f..00000000 --- a/tests/phpunit/includes/DiffHistoryBlobTest.php +++ /dev/null @@ -1,40 +0,0 @@ -markTestSkipped( 'The xdiff extension is not available' ); - return; - } - if ( !function_exists( 'xdiff_string_rabdiff' ) ) { - $this->markTestSkipped( 'The version of xdiff extension is lower than 1.5.0' ); - return; - } - if ( !extension_loaded( 'hash' ) && !extension_loaded( 'mhash' ) ) { - $this->markTestSkipped( 'Neither the hash nor mhash extension is available' ); - return; - } - } - - /** - * Test for DiffHistoryBlob::xdiffAdler32() - * @dataProvider provideXdiffAdler32 - */ - function testXdiffAdler32( $input ) { - $xdiffHash = substr( xdiff_string_rabdiff( $input, '' ), 0, 4 ); - $dhb = new DiffHistoryBlob; - $myHash = $dhb->xdiffAdler32( $input ); - $this->assertSame( bin2hex( $xdiffHash ), bin2hex( $myHash ), - "Hash of " . addcslashes( $input, "\0..\37!@\@\177..\377" ) ); - } - - function provideXdiffAdler32() { - return array( - array( '', 'Empty string' ), - array( "\0", 'Null' ), - array( "\0\0\0", "Several nulls" ), - array( "Hello", "An ASCII string" ), - array( str_repeat( "x", 6000 ), "A string larger than xdiff's NMAX (5552)" ) - ); - } -} diff --git a/tests/phpunit/includes/EditPageTest.php b/tests/phpunit/includes/EditPageTest.php deleted file mode 100644 index 8ecfd7e5..00000000 --- a/tests/phpunit/includes/EditPageTest.php +++ /dev/null @@ -1,40 +0,0 @@ -assertEquals( $title, $extracted ); - } - - function dataExtractSectionTitle() { - return array( - array( - "== Test ==\n\nJust a test section.", - "Test" - ), - array( - "An initial section, no header.", - false - ), - array( - "An initial section with a fake heder (bug 32617)\n\n== Test == ??\nwtf", - false - ), - array( - "== Section ==\nfollowed by a fake == Non-section == ??\nnoooo", - "Section" - ), - array( - "== Section== \t\r\n followed by whitespace (bug 35051)", - 'Section', - ), - ); - } -} diff --git a/tests/phpunit/includes/ExternalStoreTest.php b/tests/phpunit/includes/ExternalStoreTest.php deleted file mode 100644 index 92ec7344..00000000 --- a/tests/phpunit/includes/ExternalStoreTest.php +++ /dev/null @@ -1,32 +0,0 @@ -saved_wgExternalStores = $wgExternalStores ; - } - - function tearDown() { - global $wgExternalStores; - $wgExternalStores = $this->saved_wgExternalStores ; - } - - function testExternalStoreDoesNotFetchIncorrectURL() { - global $wgExternalStores; - $wgExternalStores = true; - - # Assertions for r68900 - $this->assertFalse( - ExternalStore::fetchFromURL( 'http://' ) ); - $this->assertFalse( - ExternalStore::fetchFromURL( 'ftp.wikimedia.org' ) ); - $this->assertFalse( - ExternalStore::fetchFromURL( '/super.txt' ) ); - } -} - diff --git a/tests/phpunit/includes/ExtraParserTest.php b/tests/phpunit/includes/ExtraParserTest.php deleted file mode 100644 index 903a6d25..00000000 --- a/tests/phpunit/includes/ExtraParserTest.php +++ /dev/null @@ -1,169 +0,0 @@ -options = new ParserOptions; - $this->options->setTemplateCallback( array( __CLASS__, 'statelessFetchTemplate' ) ); - $this->parser = new Parser; - - MagicWord::clearCache(); - } - - // Bug 8689 - Long numeric lines kill the parser - function testBug8689() { - global $wgLang; - global $wgUser; - $longLine = '1.' . str_repeat( '1234567890', 100000 ) . "\n"; - - if ( $wgLang === null ) $wgLang = new Language; - - $t = Title::newFromText( 'Unit test' ); - $options = ParserOptions::newFromUser( $wgUser ); - $this->assertEquals( "

$longLine

", - $this->parser->parse( $longLine, $t, $options )->getText() ); - } - - /* Test the parser entry points */ - function testParse() { - $title = Title::newFromText( __FUNCTION__ ); - $parserOutput = $this->parser->parse( "Test\n{{Foo}}\n{{Bar}}" , $title, $this->options ); - $this->assertEquals( "

Test\nContent of Template:Foo\nContent of Template:Bar\n

", $parserOutput->getText() ); - } - - function testPreSaveTransform() { - global $wgUser; - $title = Title::newFromText( __FUNCTION__ ); - $outputText = $this->parser->preSaveTransform( "Test\r\n{{subst:Foo}}\n{{Bar}}", $title, $wgUser, $this->options ); - - $this->assertEquals( "Test\nContent of ''Template:Foo''\n{{Bar}}", $outputText ); - } - - function testPreprocess() { - $title = Title::newFromText( __FUNCTION__ ); - $outputText = $this->parser->preprocess( "Test\n{{Foo}}\n{{Bar}}" , $title, $this->options ); - - $this->assertEquals( "Test\nContent of ''Template:Foo''\nContent of ''Template:Bar''", $outputText ); - } - - /** - * cleanSig() makes all templates substs and removes tildes - */ - function testCleanSig() { - global $wgCleanSignatures; - $oldCleanSignature = $wgCleanSignatures; - $wgCleanSignatures = true; - - $title = Title::newFromText( __FUNCTION__ ); - $outputText = $this->parser->cleanSig( "{{Foo}} ~~~~" ); - - $wgCleanSignatures = $oldCleanSignature; - - $this->assertEquals( "{{SUBST:Foo}} ", $outputText ); - } - - /** - * cleanSig() should do nothing if disabled - */ - function testCleanSigDisabled() { - global $wgCleanSignatures; - $oldCleanSignature = $wgCleanSignatures; - $wgCleanSignatures = false; - - $title = Title::newFromText( __FUNCTION__ ); - $outputText = $this->parser->cleanSig( "{{Foo}} ~~~~" ); - - $wgCleanSignatures = $oldCleanSignature; - - $this->assertEquals( "{{Foo}} ~~~~", $outputText ); - } - - /** - * cleanSigInSig() just removes tildes - * @dataProvider provideStringsForCleanSigInSig - */ - function testCleanSigInSig( $in, $out ) { - $this->assertEquals( Parser::cleanSigInSig( $in), $out ); - } - - function provideStringsForCleanSigInSig() { - return array( - array( "{{Foo}} ~~~~", "{{Foo}} " ), - array( "~~~", "" ), - array( "~~~~~", "" ), - ); - } - - function testGetSection() { - $outputText2 = $this->parser->getSection( "Section 0\n== Heading 1 ==\nSection 1\n=== Heading 2 ===\nSection 2\n== Heading 3 ==\nSection 3\n", 2 ); - $outputText1 = $this->parser->getSection( "Section 0\n== Heading 1 ==\nSection 1\n=== Heading 2 ===\nSection 2\n== Heading 3 ==\nSection 3\n", 1 ); - - $this->assertEquals( "=== Heading 2 ===\nSection 2", $outputText2 ); - $this->assertEquals( "== Heading 1 ==\nSection 1\n=== Heading 2 ===\nSection 2", $outputText1 ); - } - - function testReplaceSection() { - $outputText = $this->parser->replaceSection( "Section 0\n== Heading 1 ==\nSection 1\n=== Heading 2 ===\nSection 2\n== Heading 3 ==\nSection 3\n", 1, "New section 1" ); - - $this->assertEquals( "Section 0\nNew section 1\n\n== Heading 3 ==\nSection 3", $outputText ); - } - - /** - * Templates and comments are not affected, but noinclude/onlyinclude is. - */ - function testGetPreloadText() { - $title = Title::newFromText( __FUNCTION__ ); - $outputText = $this->parser->getPreloadText( "{{Foo}} censored information ", $title, $this->options ); - - $this->assertEquals( "{{Foo}} information ", $outputText ); - } - - static function statelessFetchTemplate( $title, $parser=false ) { - $text = "Content of ''" . $title->getFullText() . "''"; - $deps = array(); - - return array( - 'text' => $text, - 'finalTitle' => $title, - 'deps' => $deps ); - } - - /** - * @group Database - */ - function testTrackingCategory() { - $title = Title::newFromText( __FUNCTION__ ); - $catName = wfMessage( 'broken-file-category' )->inContentLanguage()->text(); - $cat = Title::makeTitleSafe( NS_CATEGORY, $catName ); - $expected = array( $cat->getDBkey() ); - $parserOutput = $this->parser->parse( "[[file:nonexistent]]" , $title, $this->options ); - $result = $parserOutput->getCategoryLinks(); - $this->assertEquals( $expected, $result ); - } - - /** - * @group Database - */ - function testTrackingCategorySpecial() { - // Special pages shouldn't have tracking cats. - $title = SpecialPage::getTitleFor( 'Contributions' ); - $parserOutput = $this->parser->parse( "[[file:nonexistent]]" , $title, $this->options ); - $result = $parserOutput->getCategoryLinks(); - $this->assertEmpty( $result ); - } - } diff --git a/tests/phpunit/includes/FauxResponseTest.php b/tests/phpunit/includes/FauxResponseTest.php deleted file mode 100644 index c0420049..00000000 --- a/tests/phpunit/includes/FauxResponseTest.php +++ /dev/null @@ -1,70 +0,0 @@ -response = new FauxResponse; - } - - function testCookie() { - $this->assertEquals( null, $this->response->getcookie( 'key' ), 'Non-existing cookie' ); - $this->response->setcookie( 'key', 'val' ); - $this->assertEquals( 'val', $this->response->getcookie( 'key' ), 'Existing cookie' ); - } - - function testHeader() { - $this->assertEquals( null, $this->response->getheader( 'Location' ), 'Non-existing header' ); - - $this->response->header( 'Location: http://localhost/' ); - $this->assertEquals( 'http://localhost/', $this->response->getheader( 'Location' ), 'Set header' ); - - $this->response->header( 'Location: http://127.0.0.1/' ); - $this->assertEquals( 'http://127.0.0.1/', $this->response->getheader( 'Location' ), 'Same header' ); - - $this->response->header( 'Location: http://127.0.0.2/', false ); - $this->assertEquals( 'http://127.0.0.1/', $this->response->getheader( 'Location' ), 'Same header with override disabled' ); - } - - function testResponseCode() { - $this->response->header( 'HTTP/1.1 200' ); - $this->assertEquals( 200, $this->response->getStatusCode(), 'Header with no message' ); - - $this->response->header( 'HTTP/1.x 201' ); - $this->assertEquals( 201, $this->response->getStatusCode(), 'Header with no message and protocol 1.x' ); - - $this->response->header( 'HTTP/1.1 202 OK' ); - $this->assertEquals( 202, $this->response->getStatusCode(), 'Normal header' ); - - $this->response->header( 'HTTP/1.x 203 OK' ); - $this->assertEquals( 203, $this->response->getStatusCode(), 'Normal header with no message and protocol 1.x' ); - - $this->response->header( 'HTTP/1.x 204 OK', false, 205 ); - $this->assertEquals( 205, $this->response->getStatusCode(), 'Third parameter overrides the HTTP/... header' ); - - $this->response->header( 'Location: http://localhost/', false, 206 ); - $this->assertEquals( 206, $this->response->getStatusCode(), 'Third parameter with another header' ); - } -} diff --git a/tests/phpunit/includes/FormOptionsInitializationTest.php b/tests/phpunit/includes/FormOptionsInitializationTest.php deleted file mode 100644 index d86c95d7..00000000 --- a/tests/phpunit/includes/FormOptionsInitializationTest.php +++ /dev/null @@ -1,85 +0,0 @@ -options; - } -} - -/** - * Test class for FormOptions initialization - * Ensure the FormOptions::add() does what we want it to do. - * - * Generated by PHPUnit on 2011-02-28 at 20:46:27. - * - * Copyright © 2011, Antoine Musso - * - * @author Antoine Musso - */ -class FormOptionsInitializationTest extends MediaWikiTestCase { - /** - * @var FormOptions - */ - protected $object; - - - /** - * A new fresh and empty FormOptions object to test initialization - * with. - */ - protected function setUp() { - $this->object = new FormOptionsExposed(); - - } - - public function testAddStringOption() { - $this->object->add( 'foo', 'string value' ); - $this->assertEquals( - array( - 'foo' => array( - 'default' => 'string value', - 'consumed' => false, - 'type' => FormOptions::STRING, - 'value' => null, - ) - ), - $this->object->getOptions() - ); - } - - public function testAddIntegers() { - $this->object->add( 'one', 1 ); - $this->object->add( 'negone', -1 ); - $this->assertEquals( - array( - 'negone' => array( - 'default' => -1, - 'value' => null, - 'consumed' => false, - 'type' => FormOptions::INT, - ), - 'one' => array( - 'default' => 1, - 'value' => null, - 'consumed' => false, - 'type' => FormOptions::INT, - ) - ), - $this->object->getOptions() - ); - } - -} diff --git a/tests/phpunit/includes/FormOptionsTest.php b/tests/phpunit/includes/FormOptionsTest.php deleted file mode 100644 index 749343ec..00000000 --- a/tests/phpunit/includes/FormOptionsTest.php +++ /dev/null @@ -1,90 +0,0 @@ -object = new FormOptions; - $this->object->add( 'string1', 'string one' ); - $this->object->add( 'string2', 'string two' ); - $this->object->add( 'integer', 0 ); - $this->object->add( 'intnull', 0, FormOptions::INTNULL ); - } - - /** Helpers for testGuessType() */ - /* @{ */ - private function assertGuessBoolean( $data ) { - $this->guess( FormOptions::BOOL, $data ); - } - private function assertGuessInt( $data ) { - $this->guess( FormOptions::INT, $data ); - } - private function assertGuessString( $data ) { - $this->guess( FormOptions::STRING, $data ); - } - - /** Generic helper */ - private function guess( $expected, $data ) { - $this->assertEquals( - $expected, - FormOptions::guessType( $data ) - ); - } - /* @} */ - - /** - * Reuse helpers above assertGuessBoolean assertGuessInt assertGuessString - */ - public function testGuessTypeDetection() { - $this->assertGuessBoolean( true ); - $this->assertGuessBoolean( false ); - - $this->assertGuessInt( 0 ); - $this->assertGuessInt( -5 ); - $this->assertGuessInt( 5 ); - $this->assertGuessInt( 0x0F ); - - $this->assertGuessString( 'true' ); - $this->assertGuessString( 'false' ); - $this->assertGuessString( '5' ); - $this->assertGuessString( '0' ); - } - - /** - * @expectedException MWException - */ - public function testGuessTypeOnArrayThrowException() { - $this->object->guessType( array( 'foo' ) ); - } - /** - * @expectedException MWException - */ - public function testGuessTypeOnNullThrowException() { - $this->object->guessType( null ); - } -} diff --git a/tests/phpunit/includes/GlobalFunctions/GlobalTest.php b/tests/phpunit/includes/GlobalFunctions/GlobalTest.php deleted file mode 100644 index 9097d301..00000000 --- a/tests/phpunit/includes/GlobalFunctions/GlobalTest.php +++ /dev/null @@ -1,598 +0,0 @@ -originals['wgReadOnlyFile'] = $wgReadOnlyFile; - $this->originals['wgUrlProtocols'] = $wgUrlProtocols; - $wgReadOnlyFile = tempnam( wfTempDir(), "mwtest_readonly" ); - $wgUrlProtocols[] = 'file://'; - unlink( $wgReadOnlyFile ); - } - - function tearDown() { - global $wgReadOnlyFile, $wgUrlProtocols; - if ( file_exists( $wgReadOnlyFile ) ) { - unlink( $wgReadOnlyFile ); - } - $wgReadOnlyFile = $this->originals['wgReadOnlyFile']; - $wgUrlProtocols = $this->originals['wgUrlProtocols']; - } - - /** @dataProvider provideForWfArrayDiff2 */ - public function testWfArrayDiff2( $a, $b, $expected ) { - $this->assertEquals( - wfArrayDiff2( $a, $b), $expected - ); - } - - // @todo Provide more tests - public function provideForWfArrayDiff2() { - // $a $b $expected - return array( - array( - array( 'a', 'b'), - array( 'a', 'b'), - array(), - ), - array( - array( array( 'a'), array( 'a', 'b', 'c' )), - array( array( 'a'), array( 'a', 'b' )), - array( 1 => array( 'a', 'b', 'c' ) ), - ), - ); - } - - function testRandom() { - # This could hypothetically fail, but it shouldn't ;) - $this->assertFalse( - wfRandom() == wfRandom() ); - } - - function testUrlencode() { - $this->assertEquals( - "%E7%89%B9%E5%88%A5:Contributions/Foobar", - wfUrlencode( "\xE7\x89\xB9\xE5\x88\xA5:Contributions/Foobar" ) ); - } - - function testExpandIRI() { - $this->assertEquals( - "https://te.wikibooks.org/wiki/ఉబుంటు_వాడుకరి_మార్గదర్శని", - wfExpandIRI( "https://te.wikibooks.org/wiki/%E0%B0%89%E0%B0%AC%E0%B1%81%E0%B0%82%E0%B0%9F%E0%B1%81_%E0%B0%B5%E0%B0%BE%E0%B0%A1%E0%B1%81%E0%B0%95%E0%B0%B0%E0%B0%BF_%E0%B0%AE%E0%B0%BE%E0%B0%B0%E0%B1%8D%E0%B0%97%E0%B0%A6%E0%B0%B0%E0%B1%8D%E0%B0%B6%E0%B0%A8%E0%B0%BF" ) ); - } - - function testReadOnlyEmpty() { - global $wgReadOnly; - $wgReadOnly = null; - - $this->assertFalse( wfReadOnly() ); - $this->assertFalse( wfReadOnly() ); - } - - function testReadOnlySet() { - global $wgReadOnly, $wgReadOnlyFile; - - $f = fopen( $wgReadOnlyFile, "wt" ); - fwrite( $f, 'Message' ); - fclose( $f ); - $wgReadOnly = null; # Check on $wgReadOnlyFile - - $this->assertTrue( wfReadOnly() ); - $this->assertTrue( wfReadOnly() ); # Check cached - - unlink( $wgReadOnlyFile ); - $wgReadOnly = null; # Clean cache - - $this->assertFalse( wfReadOnly() ); - $this->assertFalse( wfReadOnly() ); - } - - function testQuotedPrintable() { - $this->assertEquals( - "=?UTF-8?Q?=C4=88u=20legebla=3F?=", - UserMailer::quotedPrintable( "\xc4\x88u legebla?", "UTF-8" ) ); - } - - function testTime() { - $start = wfTime(); - $this->assertInternalType( 'float', $start ); - $end = wfTime(); - $this->assertTrue( $end > $start, "Time is running backwards!" ); - } - - function dataArrayToCGI() { - return array( - array( array(), '' ), // empty - array( array( 'foo' => 'bar' ), 'foo=bar' ), // string test - array( array( 'foo' => '' ), 'foo=' ), // empty string test - array( array( 'foo' => 1 ), 'foo=1' ), // number test - array( array( 'foo' => true ), 'foo=1' ), // true test - array( array( 'foo' => false ), '' ), // false test - array( array( 'foo' => null ), '' ), // null test - array( array( 'foo' => 'A&B=5+6@!"\'' ), 'foo=A%26B%3D5%2B6%40%21%22%27' ), // urlencoding test - array( array( 'foo' => 'bar', 'baz' => 'is', 'asdf' => 'qwerty' ), 'foo=bar&baz=is&asdf=qwerty' ), // multi-item test - array( array( 'foo' => array( 'bar' => 'baz' ) ), 'foo%5Bbar%5D=baz' ), - array( array( 'foo' => array( 'bar' => 'baz', 'qwerty' => 'asdf' ) ), 'foo%5Bbar%5D=baz&foo%5Bqwerty%5D=asdf' ), - array( array( 'foo' => array( 'bar', 'baz' ) ), 'foo%5B0%5D=bar&foo%5B1%5D=baz' ), - array( array( 'foo' => array( 'bar' => array( 'bar' => 'baz' ) ) ), 'foo%5Bbar%5D%5Bbar%5D=baz' ), - ); - } - - /** - * @dataProvider dataArrayToCGI - */ - function testArrayToCGI( $array, $result ) { - $this->assertEquals( $result, wfArrayToCGI( $array ) ); - } - - - function testArrayToCGI2() { - $this->assertEquals( - "baz=bar&foo=bar", - wfArrayToCGI( - array( 'baz' => 'bar' ), - array( 'foo' => 'bar', 'baz' => 'overridden value' ) ) ); - } - - function dataCgiToArray() { - return array( - array( '', array() ), // empty - array( 'foo=bar', array( 'foo' => 'bar' ) ), // string - array( 'foo=', array( 'foo' => '' ) ), // empty string - array( 'foo', array( 'foo' => '' ) ), // missing = - array( 'foo=bar&qwerty=asdf', array( 'foo' => 'bar', 'qwerty' => 'asdf' ) ), // multiple value - array( 'foo=A%26B%3D5%2B6%40%21%22%27', array( 'foo' => 'A&B=5+6@!"\'' ) ), // urldecoding test - array( 'foo%5Bbar%5D=baz', array( 'foo' => array( 'bar' => 'baz' ) ) ), - array( 'foo%5Bbar%5D=baz&foo%5Bqwerty%5D=asdf', array( 'foo' => array( 'bar' => 'baz', 'qwerty' => 'asdf' ) ) ), - array( 'foo%5B0%5D=bar&foo%5B1%5D=baz', array( 'foo' => array( 0 => 'bar', 1 => 'baz' ) ) ), - array( 'foo%5Bbar%5D%5Bbar%5D=baz', array( 'foo' => array( 'bar' => array( 'bar' => 'baz' ) ) ) ), - ); - } - - /** - * @dataProvider dataCgiToArray - */ - function testCgiToArray( $cgi, $result ) { - $this->assertEquals( $result, wfCgiToArray( $cgi ) ); - } - - function dataCgiRoundTrip() { - return array( - array( '' ), - array( 'foo=bar' ), - array( 'foo=' ), - array( 'foo=bar&baz=biz' ), - array( 'foo=A%26B%3D5%2B6%40%21%22%27' ), - array( 'foo%5Bbar%5D=baz' ), - array( 'foo%5B0%5D=bar&foo%5B1%5D=baz' ), - array( 'foo%5Bbar%5D%5Bbar%5D=baz' ), - ); - } - - /** - * @dataProvider dataCgiRoundTrip - */ - function testCgiRoundTrip( $cgi ) { - $this->assertEquals( $cgi, wfArrayToCGI( wfCgiToArray( $cgi ) ) ); - } - - function testMimeTypeMatch() { - $this->assertEquals( - 'text/html', - mimeTypeMatch( 'text/html', - array( 'application/xhtml+xml' => 1.0, - 'text/html' => 0.7, - 'text/plain' => 0.3 ) ) ); - $this->assertEquals( - 'text/*', - mimeTypeMatch( 'text/html', - array( 'image/*' => 1.0, - 'text/*' => 0.5 ) ) ); - $this->assertEquals( - '*/*', - mimeTypeMatch( 'text/html', - array( '*/*' => 1.0 ) ) ); - $this->assertNull( - mimeTypeMatch( 'text/html', - array( 'image/png' => 1.0, - 'image/svg+xml' => 0.5 ) ) ); - } - - function testNegotiateType() { - $this->assertEquals( - 'text/html', - wfNegotiateType( - array( 'application/xhtml+xml' => 1.0, - 'text/html' => 0.7, - 'text/plain' => 0.5, - 'text/*' => 0.2 ), - array( 'text/html' => 1.0 ) ) ); - $this->assertEquals( - 'application/xhtml+xml', - wfNegotiateType( - array( 'application/xhtml+xml' => 1.0, - 'text/html' => 0.7, - 'text/plain' => 0.5, - 'text/*' => 0.2 ), - array( 'application/xhtml+xml' => 1.0, - 'text/html' => 0.5 ) ) ); - $this->assertEquals( - 'text/html', - wfNegotiateType( - array( 'text/html' => 1.0, - 'text/plain' => 0.5, - 'text/*' => 0.5, - 'application/xhtml+xml' => 0.2 ), - array( 'application/xhtml+xml' => 1.0, - 'text/html' => 0.5 ) ) ); - $this->assertEquals( - 'text/html', - wfNegotiateType( - array( 'text/*' => 1.0, - 'image/*' => 0.7, - '*/*' => 0.3 ), - array( 'application/xhtml+xml' => 1.0, - 'text/html' => 0.5 ) ) ); - $this->assertNull( - wfNegotiateType( - array( 'text/*' => 1.0 ), - array( 'application/xhtml+xml' => 1.0 ) ) ); - } - - function testFallbackMbstringFunctions() { - - if( !extension_loaded( 'mbstring' ) ) { - $this->markTestSkipped( "The mb_string functions must be installed to test the fallback functions" ); - } - - $sampleUTF = "Östergötland_coat_of_arms.png"; - - - //mb_substr - $substr_params = array( - array( 0, 0 ), - array( 5, -4 ), - array( 33 ), - array( 100, -5 ), - array( -8, 10 ), - array( 1, 1 ), - array( 2, -1 ) - ); - - foreach( $substr_params as $param_set ) { - $old_param_set = $param_set; - array_unshift( $param_set, $sampleUTF ); - - $this->assertEquals( - MWFunction::callArray( 'mb_substr', $param_set ), - MWFunction::callArray( 'Fallback::mb_substr', $param_set ), - 'Fallback mb_substr with params ' . implode( ', ', $old_param_set ) - ); - } - - - //mb_strlen - $this->assertEquals( - mb_strlen( $sampleUTF ), - Fallback::mb_strlen( $sampleUTF ), - 'Fallback mb_strlen' - ); - - - //mb_str(r?)pos - $strpos_params = array( - //array( 'ter' ), - //array( 'Ö' ), - //array( 'Ö', 3 ), - //array( 'oat_', 100 ), - //array( 'c', -10 ), - //Broken for now - ); - - foreach( $strpos_params as $param_set ) { - $old_param_set = $param_set; - array_unshift( $param_set, $sampleUTF ); - - $this->assertEquals( - MWFunction::callArray( 'mb_strpos', $param_set ), - MWFunction::callArray( 'Fallback::mb_strpos', $param_set ), - 'Fallback mb_strpos with params ' . implode( ', ', $old_param_set ) - ); - - $this->assertEquals( - MWFunction::callArray( 'mb_strrpos', $param_set ), - MWFunction::callArray( 'Fallback::mb_strrpos', $param_set ), - 'Fallback mb_strrpos with params ' . implode( ', ', $old_param_set ) - ); - } - - } - - - function testDebugFunctionTest() { - - global $wgDebugLogFile, $wgDebugTimestamps; - - $old_log_file = $wgDebugLogFile; - $wgDebugLogFile = tempnam( wfTempDir(), 'mw-' ); - # @todo FIXME: This setting should be tested - $wgDebugTimestamps = false; - - - - wfDebug( "This is a normal string" ); - $this->assertEquals( "This is a normal string", file_get_contents( $wgDebugLogFile ) ); - unlink( $wgDebugLogFile ); - - - wfDebug( "This is nöt an ASCII string" ); - $this->assertEquals( "This is nöt an ASCII string", file_get_contents( $wgDebugLogFile ) ); - unlink( $wgDebugLogFile ); - - - wfDebug( "\00305This has böth UTF and control chars\003" ); - $this->assertEquals( " 05This has böth UTF and control chars ", file_get_contents( $wgDebugLogFile ) ); - unlink( $wgDebugLogFile ); - - wfDebugMem(); - $this->assertGreaterThan( 5000, preg_replace( '/\D/', '', file_get_contents( $wgDebugLogFile ) ) ); - unlink( $wgDebugLogFile ); - - wfDebugMem(true); - $this->assertGreaterThan( 5000000, preg_replace( '/\D/', '', file_get_contents( $wgDebugLogFile ) ) ); - unlink( $wgDebugLogFile ); - - - - $wgDebugLogFile = $old_log_file; - - } - - function testClientAcceptsGzipTest() { - - $settings = array( - 'gzip' => true, - 'bzip' => false, - '*' => false, - 'compress, gzip' => true, - 'gzip;q=1.0' => true, - 'foozip' => false, - 'foo*zip' => false, - 'gzip;q=abcde' => true, //is this REALLY valid? - 'gzip;q=12345678.9' => true, - ' gzip' => true, - ); - - if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) $old_server_setting = $_SERVER['HTTP_ACCEPT_ENCODING']; - - foreach ( $settings as $encoding => $expect ) { - $_SERVER['HTTP_ACCEPT_ENCODING'] = $encoding; - - $this->assertEquals( $expect, wfClientAcceptsGzip( true ), - "'$encoding' => " . wfBoolToStr( $expect ) ); - } - - if( isset( $old_server_setting ) ) $_SERVER['HTTP_ACCEPT_ENCODING'] = $old_server_setting; - - } - - - - function testSwapVarsTest() { - - - $var1 = 1; - $var2 = 2; - - $this->assertEquals( $var1, 1, 'var1 is set originally' ); - $this->assertEquals( $var2, 2, 'var1 is set originally' ); - - swap( $var1, $var2 ); - - $this->assertEquals( $var1, 2, 'var1 is swapped' ); - $this->assertEquals( $var2, 1, 'var2 is swapped' ); - - } - - - function testWfPercentTest() { - - $pcts = array( - array( 6/7, '0.86%', 2, false ), - array( 3/3, '1%' ), - array( 22/7, '3.14286%', 5 ), - array( 3/6, '0.5%' ), - array( 1/3, '0%', 0 ), - array( 10/3, '0%', -1 ), - array( 3/4/5, '0.1%', 1 ), - array( 6/7*8, '6.8571428571%', 10 ), - ); - - foreach( $pcts as $pct ) { - if( !isset( $pct[2] ) ) $pct[2] = 2; - if( !isset( $pct[3] ) ) $pct[3] = true; - - $this->assertEquals( wfPercent( $pct[0], $pct[2], $pct[3] ), $pct[1], $pct[1] ); - } - - } - - - function testInStringTest() { - - $this->assertTrue( in_string( 'foo', 'foobar' ), 'foo is in foobar' ); - $this->assertFalse( in_string( 'Bar', 'foobar' ), 'Case-sensitive by default' ); - $this->assertTrue( in_string( 'Foo', 'foobar', true ), 'Case-insensitive when asked' ); - - } - - /** - * test @see wfShorthandToInteger() - * @dataProvider provideShorthand - */ - public function testWfShorthandToInteger( $shorthand, $expected ) { - $this->assertEquals( $expected, - wfShorthandToInteger( $shorthand ) - ); - } - - /** array( shorthand, expected integer ) */ - public function provideShorthand() { - return array( - # Null, empty ... - array( '', -1), - array( ' ', -1), - array( null, -1), - - # Failures returns 0 :( - array( 'ABCDEFG', 0 ), - array( 'Ak', 0 ), - - # Int, strings with spaces - array( 1, 1 ), - array( ' 1 ', 1 ), - array( 1023, 1023 ), - array( ' 1023 ', 1023 ), - - # kilo, Mega, Giga - array( '1k', 1024 ), - array( '1K', 1024 ), - array( '1m', 1024 * 1024 ), - array( '1M', 1024 * 1024 ), - array( '1g', 1024 * 1024 * 1024 ), - array( '1G', 1024 * 1024 * 1024 ), - - # Negatives - array( -1, -1 ), - array( -500, -500 ), - array( '-500', -500 ), - array( '-1k', -1024 ), - - # Zeroes - array( '0', 0 ), - array( '0k', 0 ), - array( '0M', 0 ), - array( '0G', 0 ), - array( '-0', 0 ), - array( '-0k', 0 ), - array( '-0M', 0 ), - array( '-0G', 0 ), - ); - } - - /** - * @dataProvider provideMakeUrlIndexes() - */ - function testMakeUrlIndexes( $url, $expected ) { - $index = wfMakeUrlIndexes( $url ); - $this->assertEquals( $expected, $index, "wfMakeUrlIndexes(\"$url\")" ); - } - - function provideMakeUrlIndexes() { - return array( - array( - // just a regular :) - 'https://bugzilla.wikimedia.org/show_bug.cgi?id=28627', - array( 'https://org.wikimedia.bugzilla./show_bug.cgi?id=28627' ) - ), - array( - // mailtos are handled special - // is this really right though? that final . probably belongs earlier? - 'mailto:wiki@wikimedia.org', - array( 'mailto:org.wikimedia@wiki.' ) - ), - - // file URL cases per bug 28627... - array( - // three slashes: local filesystem path Unix-style - 'file:///whatever/you/like.txt', - array( 'file://./whatever/you/like.txt' ) - ), - array( - // three slashes: local filesystem path Windows-style - 'file:///c:/whatever/you/like.txt', - array( 'file://./c:/whatever/you/like.txt' ) - ), - array( - // two slashes: UNC filesystem path Windows-style - 'file://intranet/whatever/you/like.txt', - array( 'file://intranet./whatever/you/like.txt' ) - ), - // Multiple-slash cases that can sorta work on Mozilla - // if you hack it just right are kinda pathological, - // and unreliable cross-platform or on IE which means they're - // unlikely to appear on intranets. - // - // Those will survive the algorithm but with results that - // are less consistent. - - // protocol-relative URL cases per bug 29854... - array( - '//bugzilla.wikimedia.org/show_bug.cgi?id=28627', - array( - 'http://org.wikimedia.bugzilla./show_bug.cgi?id=28627', - 'https://org.wikimedia.bugzilla./show_bug.cgi?id=28627' - ) - ), - ); - } - - /** - * @dataProvider provideWfMatchesDomainList - */ - function testWfMatchesDomainList( $url, $domains, $expected, $description ) { - $actual = wfMatchesDomainList( $url, $domains ); - $this->assertEquals( $expected, $actual, $description ); - } - - function provideWfMatchesDomainList() { - $a = array(); - $protocols = array( 'HTTP' => 'http:', 'HTTPS' => 'https:', 'protocol-relative' => '' ); - foreach ( $protocols as $pDesc => $p ) { - $a = array_merge( $a, array( - array( "$p//www.example.com", array(), false, "No matches for empty domains array, $pDesc URL" ), - array( "$p//www.example.com", array( 'www.example.com' ), true, "Exact match in domains array, $pDesc URL" ), - array( "$p//www.example.com", array( 'example.com' ), true, "Match without subdomain in domains array, $pDesc URL" ), - array( "$p//www.example2.com", array( 'www.example.com', 'www.example2.com', 'www.example3.com' ), true, "Exact match with other domains in array, $pDesc URL" ), - array( "$p//www.example2.com", array( 'example.com', 'example2.com', 'example3,com' ), true, "Match without subdomain with other domains in array, $pDesc URL" ), - array( "$p//www.example4.com", array( 'example.com', 'example2.com', 'example3,com' ), false, "Domain not in array, $pDesc URL" ), - - // FIXME: This is a bug in wfMatchesDomainList(). If and when this is fixed, update this test case - array( "$p//nds-nl.wikipedia.org", array( 'nl.wikipedia.org' ), true, "Substrings of domains match while they shouldn't, $pDesc URL" ), - ) ); - } - return $a; - } - - /** - * @dataProvider provideWfShellMaintenanceCmdList - */ - function testWfShellMaintenanceCmd( $script, $parameters, $options, $expected, $description ) { - if( wfIsWindows() ) { - // Approximation that's good enough for our purposes just now - $expected = str_replace( "'", '"', $expected ); - } - $actual = wfShellMaintenanceCmd( $script, $parameters, $options ); - $this->assertEquals( $expected, $actual, $description ); - } - - function provideWfShellMaintenanceCmdList() { - global $wgPhpCli; - return array( - array( 'eval.php', array( '--help', '--test' ), array(), - "'$wgPhpCli' 'eval.php' '--help' '--test'", - "Called eval.php --help --test" ), - array( 'eval.php', array( '--help', '--test space' ), array('php' => 'php5'), - "'php5' 'eval.php' '--help' '--test space'", - "Called eval.php --help --test with php option" ), - array( 'eval.php', array( '--help', '--test', 'X' ), array('wrapper' => 'MWScript.php'), - "'$wgPhpCli' 'MWScript.php' 'eval.php' '--help' '--test' 'X'", - "Called eval.php --help --test with wrapper option" ), - array( 'eval.php', array( '--help', '--test', 'y' ), array('php' => 'php5', 'wrapper' => 'MWScript.php'), - "'php5' 'MWScript.php' 'eval.php' '--help' '--test' 'y'", - "Called eval.php --help --test with wrapper and php option" ), - ); - } - /* TODO: many more! */ -} - diff --git a/tests/phpunit/includes/GlobalFunctions/GlobalWithDBTest.php b/tests/phpunit/includes/GlobalFunctions/GlobalWithDBTest.php deleted file mode 100644 index 4879a38d..00000000 --- a/tests/phpunit/includes/GlobalFunctions/GlobalWithDBTest.php +++ /dev/null @@ -1,29 +0,0 @@ -assertEquals( $expected, wfIsBadImage( $name, $title, $blacklist ), $desc ); - } - - function provideWfIsBadImageList() { - $blacklist = '* [[File:Bad.jpg]] except [[Nasty page]]'; - return array( - array( 'Bad.jpg', false, $blacklist, true, - 'Called on a bad image' ), - array( 'Bad.jpg', Title::makeTitle( NS_MAIN, 'A page' ), $blacklist, true, - 'Called on a bad image' ), - array( 'NotBad.jpg', false, $blacklist, false, - 'Called on a non-bad image' ), - array( 'Bad.jpg', Title::makeTitle( NS_MAIN, 'Nasty page' ), $blacklist, false, - 'Called on a bad image but is on a whitelisted page' ), - array( 'File:Bad.jpg', false, $blacklist, false, - 'Called on a bad image with File:' ), - ); - } -} diff --git a/tests/phpunit/includes/GlobalFunctions/README b/tests/phpunit/includes/GlobalFunctions/README deleted file mode 100644 index 0042bdac..00000000 --- a/tests/phpunit/includes/GlobalFunctions/README +++ /dev/null @@ -1,2 +0,0 @@ -This directory hold tests for includes/GlobalFunctions.php file -which is a pile of functions. diff --git a/tests/phpunit/includes/GlobalFunctions/wfAssembleUrlTest.php b/tests/phpunit/includes/GlobalFunctions/wfAssembleUrlTest.php deleted file mode 100644 index be6c99e7..00000000 --- a/tests/phpunit/includes/GlobalFunctions/wfAssembleUrlTest.php +++ /dev/null @@ -1,111 +0,0 @@ -assertEquals( - $output, - wfAssembleUrl( $parts ), - "Testing $partsDump assembles to $output" - ); - } - - /** - * Provider of URL parts for testing wfAssembleUrl() - * - * @return array - */ - public function provideURLParts() { - $schemes = array( - '' => array(), - '//' => array( - 'delimiter' => '//', - ), - 'http://' => array( - 'scheme' => 'http', - 'delimiter' => '://', - ), - ); - - $hosts = array( - '' => array(), - 'example.com' => array( - 'host' => 'example.com', - ), - 'example.com:123' => array( - 'host' => 'example.com', - 'port' => 123, - ), - 'id@example.com' => array( - 'user' => 'id', - 'host' => 'example.com', - ), - 'id@example.com:123' => array( - 'user' => 'id', - 'host' => 'example.com', - 'port' => 123, - ), - 'id:key@example.com' => array( - 'user' => 'id', - 'pass' => 'key', - 'host' => 'example.com', - ), - 'id:key@example.com:123' => array( - 'user' => 'id', - 'pass' => 'key', - 'host' => 'example.com', - 'port' => 123, - ), - ); - - $cases = array(); - foreach ( $schemes as $scheme => $schemeParts ) { - foreach ( $hosts as $host => $hostParts ) { - foreach ( array( '', '/path' ) as $path ) { - foreach ( array( '', 'query' ) as $query ) { - foreach ( array( '', 'fragment' ) as $fragment ) { - $parts = array_merge( - $schemeParts, - $hostParts - ); - $url = $scheme . - $host . - $path; - - if ( $path ) { - $parts['path'] = $path; - } - if ( $query ) { - $parts['query'] = $query; - $url .= '?' . $query; - } - if( $fragment ) { - $parts['fragment'] = $fragment; - $url .= '#' . $fragment; - } - - - $cases[] = array( - $parts, - $url, - ); - } - } - } - } - } - - $complexURL = 'http://id:key@example.org:321' . - '/over/there?name=ferret&foo=bar#nose'; - $cases[] = array( - wfParseUrl( $complexURL ), - $complexURL, - ); - - return $cases; - } -} diff --git a/tests/phpunit/includes/GlobalFunctions/wfBCP47Test.php b/tests/phpunit/includes/GlobalFunctions/wfBCP47Test.php deleted file mode 100644 index f4ec7a5f..00000000 --- a/tests/phpunit/includes/GlobalFunctions/wfBCP47Test.php +++ /dev/null @@ -1,133 +0,0 @@ -assertEquals( $expected, wfBCP47($code), - "Applying BCP47 standard to lower case '$code'" - ); - - $code = strtoupper( $code ); - $this->assertEquals( $expected, wfBCP47($code), - "Applying BCP47 standard to upper case '$code'" - ); - } - - /** - * Array format is ($code, $expected) - */ - function provideLanguageCodes() { - return array( - // Extracted from BCP47 (list not exhaustive) - # 2.1.1 - array( 'en-ca-x-ca' , 'en-CA-x-ca' ), - array( 'sgn-be-fr' , 'sgn-BE-FR' ), - array( 'az-latn-x-latn', 'az-Latn-x-latn' ), - # 2.2 - array( 'sr-Latn-RS', 'sr-Latn-RS' ), - array( 'az-arab-ir', 'az-Arab-IR' ), - - # 2.2.5 - array( 'sl-nedis' , 'sl-nedis' ), - array( 'de-ch-1996', 'de-CH-1996' ), - - # 2.2.6 - array( - 'en-latn-gb-boont-r-extended-sequence-x-private', - 'en-Latn-GB-boont-r-extended-sequence-x-private' - ), - - // Examples from BCP47 Appendix A - # Simple language subtag: - array( 'DE', 'de' ), - array( 'fR', 'fr' ), - array( 'ja', 'ja' ), - - # Language subtag plus script subtag: - array( 'zh-hans', 'zh-Hans'), - array( 'sr-cyrl', 'sr-Cyrl'), - array( 'sr-latn', 'sr-Latn'), - - # Extended language subtags and their primary language subtag - # counterparts: - array( 'zh-cmn-hans-cn', 'zh-cmn-Hans-CN' ), - array( 'cmn-hans-cn' , 'cmn-Hans-CN' ), - array( 'zh-yue-hk' , 'zh-yue-HK' ), - array( 'yue-hk' , 'yue-HK' ), - - # Language-Script-Region: - array( 'zh-hans-cn', 'zh-Hans-CN' ), - array( 'sr-latn-RS', 'sr-Latn-RS' ), - - # Language-Variant: - array( 'sl-rozaj' , 'sl-rozaj' ), - array( 'sl-rozaj-biske', 'sl-rozaj-biske' ), - array( 'sl-nedis' , 'sl-nedis' ), - - # Language-Region-Variant: - array( 'de-ch-1901' , 'de-CH-1901' ), - array( 'sl-it-nedis' , 'sl-IT-nedis' ), - - # Language-Script-Region-Variant: - array( 'hy-latn-it-arevela', 'hy-Latn-IT-arevela' ), - - # Language-Region: - array( 'de-de' , 'de-DE' ), - array( 'en-us' , 'en-US' ), - array( 'es-419', 'es-419'), - - # Private use subtags: - array( 'de-ch-x-phonebk' , 'de-CH-x-phonebk' ), - array( 'az-arab-x-aze-derbend', 'az-Arab-x-aze-derbend' ), - /** - * Previous test does not reflect the BCP which states: - * az-Arab-x-AZE-derbend - * AZE being private, it should be lower case, hence the test above - * should probably be: - #array( 'az-arab-x-aze-derbend', 'az-Arab-x-AZE-derbend' ), - */ - - # Private use registry values: - array( 'x-whatever', 'x-whatever' ), - array( 'qaa-qaaa-qm-x-southern', 'qaa-Qaaa-QM-x-southern' ), - array( 'de-qaaa' , 'de-Qaaa' ), - array( 'sr-latn-qm', 'sr-Latn-QM' ), - array( 'sr-qaaa-rs', 'sr-Qaaa-RS' ), - - # Tags that use extensions - array( 'en-us-u-islamcal', 'en-US-u-islamcal' ), - array( 'zh-cn-a-myext-x-private', 'zh-CN-a-myext-x-private' ), - array( 'en-a-myext-b-another', 'en-a-myext-b-another' ), - - # Invalid: - // de-419-DE - // a-DE - // ar-a-aaa-b-bbb-a-ccc - - /* - // ISO 15924 : - array( 'sr-Cyrl', 'sr-Cyrl' ), - # @todo FIXME: Fix our function? - array( 'SR-lATN', 'sr-Latn' ), - array( 'fr-latn', 'fr-Latn' ), - // Use lowercase for single segment - // ISO 3166-1-alpha-2 code - array( 'US', 'us' ), # USA - array( 'uS', 'us' ), # USA - array( 'Fr', 'fr' ), # France - array( 'va', 'va' ), # Holy See (Vatican City State) - */); - } -} diff --git a/tests/phpunit/includes/GlobalFunctions/wfBaseNameTest.php b/tests/phpunit/includes/GlobalFunctions/wfBaseNameTest.php deleted file mode 100644 index 59954b23..00000000 --- a/tests/phpunit/includes/GlobalFunctions/wfBaseNameTest.php +++ /dev/null @@ -1,36 +0,0 @@ -assertEquals( $basename, wfBaseName( $fullpath ), - "wfBaseName('$fullpath') => '$basename'" ); - } - - function providePaths() { - return array( - array( '', '' ), - array( '/', '' ), - array( '\\', '' ), - array( '//', '' ), - array( '\\\\', '' ), - array( 'a', 'a' ), - array( 'aaaa', 'aaaa' ), - array( '/a', 'a' ), - array( '\\a', 'a' ), - array( '/aaaa', 'aaaa' ), - array( '\\aaaa', 'aaaa' ), - array( '/aaaa/', 'aaaa' ), - array( '\\aaaa\\', 'aaaa' ), - array( '\\aaaa\\', 'aaaa' ), - array( '/mnt/upload3/wikipedia/en/thumb/8/8b/Zork_Grand_Inquisitor_box_cover.jpg/93px-Zork_Grand_Inquisitor_box_cover.jpg', - '93px-Zork_Grand_Inquisitor_box_cover.jpg' ), - array( 'C:\\Progra~1\\Wikime~1\\Wikipe~1\\VIEWER.EXE', 'VIEWER.EXE' ), - array( 'Östergötland_coat_of_arms.png', 'Östergötland_coat_of_arms.png' ), - ); - } -} diff --git a/tests/phpunit/includes/GlobalFunctions/wfExpandUrlTest.php b/tests/phpunit/includes/GlobalFunctions/wfExpandUrlTest.php deleted file mode 100644 index 192689f8..00000000 --- a/tests/phpunit/includes/GlobalFunctions/wfExpandUrlTest.php +++ /dev/null @@ -1,80 +0,0 @@ -assertEquals( $fullUrl, wfExpandUrl( $shortUrl, $defaultProto ), $message ); - - // Restore $wgServer and $wgCanonicalServer - $wgServer = $oldServer; - $wgCanonicalServer = $oldCanServer; - } - - /** - * Provider of URL examples for testing wfExpandUrl() - * - * @return array - */ - public function provideExpandableUrls() { - $modes = array( 'http', 'https' ); - $servers = array( 'http' => 'http://example.com', 'https' => 'https://example.com', 'protocol-relative' => '//example.com' ); - $defaultProtos = array( 'http' => PROTO_HTTP, 'https' => PROTO_HTTPS, 'protocol-relative' => PROTO_RELATIVE, 'current' => PROTO_CURRENT, 'canonical' => PROTO_CANONICAL ); - - $retval = array(); - foreach ( $modes as $mode ) { - $httpsMode = $mode == 'https'; - foreach ( $servers as $serverDesc => $server ) { - foreach ( $modes as $canServerMode ) { - $canServer = "$canServerMode://example2.com"; - foreach ( $defaultProtos as $protoDesc => $defaultProto ) { - $retval[] = array( 'http://example.com', 'http://example.com', $defaultProto, $server, $canServer, $httpsMode, "Testing fully qualified http URLs (no need to expand) (defaultProto: $protoDesc , wgServer: $server, wgCanonicalServer: $canServer, current request protocol: $mode )" ); - $retval[] = array( 'https://example.com', 'https://example.com', $defaultProto, $server, $canServer, $httpsMode, "Testing fully qualified https URLs (no need to expand) (defaultProto: $protoDesc , wgServer: $server, wgCanonicalServer: $canServer, current request protocol: $mode )" ); - # Would be nice to support this, see fixme on wfExpandUrl() - $retval[] = array( "wiki/FooBar", 'wiki/FooBar', $defaultProto, $server, $canServer, $httpsMode, "Test non-expandable relative URLs (defaultProto: $protoDesc , wgServer: $server, wgCanonicalServer: $canServer, current request protocol: $mode )" ); - - // Determine expected protocol - $p = $protoDesc . ':'; // default case - if ( $protoDesc == 'protocol-relative' ) { - $p = ''; - } elseif ( $protoDesc == 'current' ) { - $p = "$mode:"; - } elseif ( $protoDesc == 'canonical' ) { - $p = "$canServerMode:"; - } else { - $p = $protoDesc . ':'; - } - // Determine expected server name - if ( $protoDesc == 'canonical' ) { - $srv = $canServer; - } elseif ( $serverDesc == 'protocol-relative' ) { - $srv = $p . $server; - } else { - $srv = $server; - } - - $retval[] = array( "$p//wikipedia.org", '//wikipedia.org', $defaultProto, $server, $canServer, $httpsMode, "Test protocol-relative URL (defaultProto: $protoDesc, wgServer: $server, wgCanonicalServer: $canServer, current request protocol: $mode )" ); - $retval[] = array( "$srv/wiki/FooBar", '/wiki/FooBar', $defaultProto, $server, $canServer, $httpsMode, "Testing expanding URL beginning with / (defaultProto: $protoDesc , wgServer: $server, wgCanonicalServer: $canServer, current request protocol: $mode )" ); - } - } - } - } - return $retval; - } -} diff --git a/tests/phpunit/includes/GlobalFunctions/wfGetCallerTest.php b/tests/phpunit/includes/GlobalFunctions/wfGetCallerTest.php deleted file mode 100644 index 4c4c4c04..00000000 --- a/tests/phpunit/includes/GlobalFunctions/wfGetCallerTest.php +++ /dev/null @@ -1,35 +0,0 @@ -assertEquals( __METHOD__, wfGetCaller( 1 ) ); - } - - function callerOne() { - return wfGetCaller(); - } - - function testOne() { - $this->assertEquals( "wfGetCaller::testOne", self::callerOne() ); - } - - function intermediateFunction( $level = 2, $n = 0 ) { - if ( $n > 0 ) - return self::intermediateFunction( $level, $n - 1 ); - return wfGetCaller( $level ); - } - - function testTwo() { - $this->assertEquals( "wfGetCaller::testTwo", self::intermediateFunction() ); - } - - function testN() { - $this->assertEquals( "wfGetCaller::testN", self::intermediateFunction( 2, 0 ) ); - $this->assertEquals( "wfGetCaller::intermediateFunction", self::intermediateFunction( 1, 0 ) ); - - for ($i=0; $i < 10; $i++) - $this->assertEquals( "wfGetCaller::intermediateFunction", self::intermediateFunction( $i + 1, $i ) ); - } -} - diff --git a/tests/phpunit/includes/GlobalFunctions/wfRemoveDotSegmentsTest.php b/tests/phpunit/includes/GlobalFunctions/wfRemoveDotSegmentsTest.php deleted file mode 100644 index 1cf0e0fb..00000000 --- a/tests/phpunit/includes/GlobalFunctions/wfRemoveDotSegmentsTest.php +++ /dev/null @@ -1,90 +0,0 @@ -assertEquals( - $outputPath, - wfRemoveDotSegments( $inputPath ), - "Testing $inputPath expands to $outputPath" - ); - } - - /** - * Provider of URL paths for testing wfRemoveDotSegments() - * - * @return array - */ - public function providePaths() { - return array( - array( '/a/b/c/./../../g', '/a/g' ), - array( 'mid/content=5/../6', 'mid/6' ), - array( '/a//../b', '/a/b' ), - array( '/.../a', '/.../a' ), - array( '.../a', '.../a' ), - array( '', '' ), - array( '/', '/' ), - array( '//', '//' ), - array( '.', '' ), - array( '..', '' ), - array( '...', '...' ), - array( '/.', '/' ), - array( '/..', '/' ), - array( './', '' ), - array( '../', '' ), - array( './a', 'a' ), - array( '../a', 'a' ), - array( '../../a', 'a' ), - array( '.././a', 'a' ), - array( './../a', 'a' ), - array( '././a', 'a' ), - array( '../../', '' ), - array( '.././', '' ), - array( './../', '' ), - array( '././', '' ), - array( '../..', '' ), - array( '../.', '' ), - array( './..', '' ), - array( './.', '' ), - array( '/../../a', '/a' ), - array( '/.././a', '/a' ), - array( '/./../a', '/a' ), - array( '/././a', '/a' ), - array( '/../../', '/' ), - array( '/.././', '/' ), - array( '/./../', '/' ), - array( '/././', '/' ), - array( '/../..', '/' ), - array( '/../.', '/' ), - array( '/./..', '/' ), - array( '/./.', '/' ), - array( 'b/../../a', '/a' ), - array( 'b/.././a', '/a' ), - array( 'b/./../a', '/a' ), - array( 'b/././a', 'b/a' ), - array( 'b/../../', '/' ), - array( 'b/.././', '/' ), - array( 'b/./../', '/' ), - array( 'b/././', 'b/' ), - array( 'b/../..', '/' ), - array( 'b/../.', '/' ), - array( 'b/./..', '/' ), - array( 'b/./.', 'b/' ), - array( '/b/../../a', '/a' ), - array( '/b/.././a', '/a' ), - array( '/b/./../a', '/a' ), - array( '/b/././a', '/b/a' ), - array( '/b/../../', '/' ), - array( '/b/.././', '/' ), - array( '/b/./../', '/' ), - array( '/b/././', '/b/' ), - array( '/b/../..', '/' ), - array( '/b/../.', '/' ), - array( '/b/./..', '/' ), - array( '/b/./.', '/b/' ), - ); - } -} diff --git a/tests/phpunit/includes/GlobalFunctions/wfShorthandToIntegerTest.php b/tests/phpunit/includes/GlobalFunctions/wfShorthandToIntegerTest.php deleted file mode 100644 index 1df26d2c..00000000 --- a/tests/phpunit/includes/GlobalFunctions/wfShorthandToIntegerTest.php +++ /dev/null @@ -1,28 +0,0 @@ -assertEquals( - wfShorthandToInteger( $input ), - $output, - $description - ); - } - - function provideABunchOfShorthands() { - return array( - array( '', -1, 'Empty string' ), - array( ' ', -1, 'String of spaces' ), - array( '1G', 1024 * 1024 * 1024, 'One gig uppercased' ), - array( '1g', 1024 * 1024 * 1024, 'One gig lowercased' ), - array( '1M', 1024 * 1024, 'One meg uppercased' ), - array( '1m', 1024 * 1024, 'One meg lowercased' ), - array( '1K', 1024, 'One kb uppercased' ), - array( '1k', 1024, 'One kb lowercased' ), - ); - } - -} diff --git a/tests/phpunit/includes/GlobalFunctions/wfTimestampTest.php b/tests/phpunit/includes/GlobalFunctions/wfTimestampTest.php deleted file mode 100644 index 505c28c7..00000000 --- a/tests/phpunit/includes/GlobalFunctions/wfTimestampTest.php +++ /dev/null @@ -1,134 +0,0 @@ -assertEquals( $output, wfTimestamp( $format, $input ), $desc ); - } - - function provideNormalTimestamps() { - $t = gmmktime( 12, 34, 56, 1, 15, 2001 ); - return array ( - // TS_UNIX - array( $t, TS_MW, '20010115123456', 'TS_UNIX to TS_MW' ), - array( -30281104, TS_MW, '19690115123456', 'Negative TS_UNIX to TS_MW' ), - array( $t, TS_UNIX, 979562096, 'TS_UNIX to TS_UNIX' ), - array( $t, TS_DB, '2001-01-15 12:34:56', 'TS_UNIX to TS_DB' ), - - array( $t, TS_ISO_8601_BASIC, '20010115T123456Z', 'TS_ISO_8601_BASIC to TS_DB' ), - - // TS_MW - array( '20010115123456', TS_MW, '20010115123456', 'TS_MW to TS_MW' ), - array( '20010115123456', TS_UNIX, 979562096, 'TS_MW to TS_UNIX' ), - array( '20010115123456', TS_DB, '2001-01-15 12:34:56', 'TS_MW to TS_DB' ), - array( '20010115123456', TS_ISO_8601_BASIC, '20010115T123456Z', 'TS_MW to TS_ISO_8601_BASIC' ), - - // TS_DB - array( '2001-01-15 12:34:56', TS_MW, '20010115123456', 'TS_DB to TS_MW' ), - array( '2001-01-15 12:34:56', TS_UNIX, 979562096, 'TS_DB to TS_UNIX' ), - array( '2001-01-15 12:34:56', TS_DB, '2001-01-15 12:34:56', 'TS_DB to TS_DB' ), - array( '2001-01-15 12:34:56', TS_ISO_8601_BASIC, '20010115T123456Z', 'TS_DB to TS_ISO_8601_BASIC' ), - - # rfc2822 section 3.3 - array( '20010115123456', TS_RFC2822, 'Mon, 15 Jan 2001 12:34:56 GMT', 'TS_MW to TS_RFC2822' ), - array( 'Mon, 15 Jan 2001 12:34:56 GMT', TS_MW, '20010115123456', 'TS_RFC2822 to TS_MW' ), - array( ' Mon, 15 Jan 2001 12:34:56 GMT', TS_MW, '20010115123456', 'TS_RFC2822 with leading space to TS_MW' ), - array( '15 Jan 2001 12:34:56 GMT', TS_MW, '20010115123456', 'TS_RFC2822 without optional day-of-week to TS_MW' ), - - # FWS = ([*WSP CRLF] 1*WSP) / obs-FWS ; Folding white space - # obs-FWS = 1*WSP *(CRLF 1*WSP) ; Section 4.2 - array( 'Mon, 15 Jan 2001 12:34:56 GMT', TS_MW, '20010115123456', 'TS_RFC2822 to TS_MW' ), - - # WSP = SP / HTAB ; rfc2234 - array( "Mon, 15 Jan\x092001 12:34:56 GMT", TS_MW, '20010115123456', 'TS_RFC2822 with HTAB to TS_MW' ), - array( "Mon, 15 Jan\x09 \x09 2001 12:34:56 GMT", TS_MW, '20010115123456', 'TS_RFC2822 with HTAB and SP to TS_MW' ), - array( 'Sun, 6 Nov 94 08:49:37 GMT', TS_MW, '19941106084937', 'TS_RFC2822 with obsolete year to TS_MW' ), - ); - } - - /** - * This test checks wfTimestamp() with values outside. - * It needs PHP 64 bits or PHP > 5.1. - * See r74778 and bug 25451 - * @dataProvider provideOldTimestamps - */ - function testOldTimestamps( $input, $format, $output, $desc ) { - $this->assertEquals( $output, wfTimestamp( $format, $input ), $desc ); - } - - function provideOldTimestamps() { - return array ( - array( '19011213204554', TS_RFC2822, 'Fri, 13 Dec 1901 20:45:54 GMT', 'Earliest time according to php documentation' ), - array( '20380119031407', TS_RFC2822, 'Tue, 19 Jan 2038 03:14:07 GMT', 'Latest 32 bit time' ), - array( '19011213204552', TS_UNIX, '-2147483648', 'Earliest 32 bit unix time' ), - array( '20380119031407', TS_UNIX, '2147483647', 'Latest 32 bit unix time' ), - array( '19011213204552', TS_RFC2822, 'Fri, 13 Dec 1901 20:45:52 GMT', 'Earliest 32 bit time' ), - array( '19011213204551', TS_RFC2822, 'Fri, 13 Dec 1901 20:45:51 GMT', 'Earliest 32 bit time - 1' ), - array( '20380119031408', TS_RFC2822, 'Tue, 19 Jan 2038 03:14:08 GMT', 'Latest 32 bit time + 1' ), - array( '19011212000000', TS_MW, '19011212000000', 'Convert to itself r74778#c10645' ), - array( '19011213204551', TS_UNIX, '-2147483649', 'Earliest 32 bit unix time - 1' ), - array( '20380119031408', TS_UNIX, '2147483648', 'Latest 32 bit unix time + 1' ), - array( '-2147483649', TS_MW, '19011213204551', '1901 negative unix time to MediaWiki' ), - array( '-5331871504', TS_MW, '18010115123456', '1801 negative unix time to MediaWiki' ), - array( '0117-08-09 12:34:56', TS_RFC2822, 'Tue, 09 Aug 0117 12:34:56 GMT', 'Death of Roman Emperor [[Trajan]]' ), - - /* @todo FIXME: 00 to 101 years are taken as being in [1970-2069] */ - array( '-58979923200', TS_RFC2822, 'Sun, 01 Jan 0101 00:00:00 GMT', '1/1/101' ), - array( '-62135596800', TS_RFC2822, 'Mon, 01 Jan 0001 00:00:00 GMT', 'Year 1' ), - - /* It is not clear if we should generate a year 0 or not - * We are completely off RFC2822 requirement of year being - * 1900 or later. - */ - array( '-62142076800', TS_RFC2822, 'Wed, 18 Oct 0000 00:00:00 GMT', 'ISO 8601:2004 [[year 0]], also called [[1 BC]]' ), - ); - } - - /** - * The Resource Loader uses wfTimestamp() to convert timestamps - * from If-Modified-Since header. Thus it must be able to parse all - * rfc2616 date formats - * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 - * @dataProvider provideHttpDates - */ - function testHttpDate( $input, $output, $desc ) { - $this->assertEquals( $output, wfTimestamp( TS_MW, $input ), $desc ); - } - - function provideHttpDates() { - return array( - array( 'Sun, 06 Nov 1994 08:49:37 GMT', '19941106084937', 'RFC 822 date' ), - array( 'Sunday, 06-Nov-94 08:49:37 GMT', '19941106084937', 'RFC 850 date' ), - array( 'Sun Nov 6 08:49:37 1994', '19941106084937', "ANSI C's asctime() format" ), - // See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html and r77171 - array( 'Mon, 22 Nov 2010 14:12:42 GMT; length=52626', '20101122141242', 'Netscape extension to HTTP/1.0' ), - ); - } - - /** - * There are a number of assumptions in our codebase where wfTimestamp() - * should give the current date but it is not given a 0 there. See r71751 CR - */ - function testTimestampParameter() { - $now = wfTimestamp( TS_UNIX ); - // We check that wfTimestamp doesn't return false (error) and use a LessThan assert - // for the cases where the test is run in a second boundary. - - $zero = wfTimestamp( TS_UNIX, 0 ); - $this->assertNotEquals( false, $zero ); - $this->assertLessThan( 5, $zero - $now ); - - $empty = wfTimestamp( TS_UNIX, '' ); - $this->assertNotEquals( false, $empty ); - $this->assertLessThan( 5, $empty - $now ); - - $null = wfTimestamp( TS_UNIX, null ); - $this->assertNotEquals( false, $null ); - $this->assertLessThan( 5, $null - $now ); - } -} diff --git a/tests/phpunit/includes/GlobalFunctions/wfUrlencodeTest.php b/tests/phpunit/includes/GlobalFunctions/wfUrlencodeTest.php deleted file mode 100644 index cd1a8dbd..00000000 --- a/tests/phpunit/includes/GlobalFunctions/wfUrlencodeTest.php +++ /dev/null @@ -1,120 +0,0 @@ - wfUrlencode() - * - * The function only need a string parameter and might react to IIS7.0 - */ - -class wfUrlencodeTest extends MediaWikiTestCase { - - #### TESTS ############################################################## - - /** @dataProvider provideURLS */ - public function testEncodingUrlWith( $input, $expected ) { - $this->verifyEncodingFor( 'Apache', $input, $expected ); - } - - /** @dataProvider provideURLS */ - public function testEncodingUrlWithMicrosoftIis7( $input, $expected ) { - $this->verifyEncodingFor( 'Microsoft-IIS/7', $input, $expected ); - } - - #### HELPERS ############################################################# - - /** - * Internal helper that actually run the test. - * Called by the public methods testEncodingUrlWith...() - * - */ - private function verifyEncodingFor( $server, $input, $expectations ) { - $expected = $this->extractExpect( $server, $expectations ); - - // save up global - $old = isset($_SERVER['SERVER_SOFTWARE']) - ? $_SERVER['SERVER_SOFTWARE'] - : null - ; - $_SERVER['SERVER_SOFTWARE'] = $server; - wfUrlencode( null ); - - // do the requested test - $this->assertEquals( - $expected, - wfUrlencode( $input ), - "Encoding '$input' for server '$server' should be '$expected'" - ); - - // restore global - if( $old === null ) { - unset( $_SERVER['SERVER_SOFTWARE'] ); - } else { - $_SERVER['SERVER_SOFTWARE'] = $old; - } - wfUrlencode( null ); - } - - /** - * Interprets the provider array. Return expected value depending - * the HTTP server name. - */ - private function extractExpect( $server, $expectations ) { - if( is_string( $expectations ) ) { - return $expectations; - } elseif( is_array( $expectations ) ) { - if( !array_key_exists( $server, $expectations ) ) { - throw new MWException( __METHOD__ . " expectation does not have any value for server name $server. Check the provider array.\n" ); - } else { - return $expectations[$server]; - } - } else { - throw new MWException( __METHOD__ . " given invalid expectation for '$server'. Should be a string or an array( => ).\n" ); - } - } - - - #### PROVIDERS ########################################################### - - /** - * Format is either: - * array( 'input', 'expected' ); - * Or: - * array( 'input', - * array( 'Apache', 'expected' ), - * array( 'Microsoft-IIS/7', 'expected' ), - * ), - * If you want to add other HTTP server name, you will have to add a new - * testing method much like the testEncodingUrlWith() method above. - */ - public function provideURLS() { - return array( - ### RFC 1738 chars - // + is not safe - array( '+', '%2B' ), - // & and = not safe in queries - array( '&', '%26' ), - array( '=', '%3D' ), - - array( ':', array( - 'Apache' => ':', - 'Microsoft-IIS/7' => '%3A', - ) ), - - // remaining chars do not need encoding - array( - ';@$-_.!*', - ';@$-_.!*', - ), - - ### Other tests - // slash remain unchanged. %2F seems to break things - array( '/', '/' ), - - // Other 'funnies' chars - array( '[]', '%5B%5D' ), - array( '<>', '%3C%3E' ), - - // Apostrophe is encoded - array( '\'', '%27' ), - ); - } -} diff --git a/tests/phpunit/includes/HooksTest.php b/tests/phpunit/includes/HooksTest.php deleted file mode 100644 index 2f9d9f8d..00000000 --- a/tests/phpunit/includes/HooksTest.php +++ /dev/null @@ -1,102 +0,0 @@ -assertEquals( 'fOO', $foo, 'Standard method' ); - $foo = 'Foo'; - - $wgHooks['MediaWikiHooksTest001'][] = $i; - - wfRunHooks( 'MediaWikiHooksTest001', array( &$foo, &$bar ) ); - - $this->assertEquals( 'foo', $foo, 'onEventName style' ); - $foo = 'Foo'; - - $wgHooks['MediaWikiHooksTest001'][] = array( $i, 'someNonStaticWithData', 'baz' ); - - wfRunHooks( 'MediaWikiHooksTest001', array( &$foo, &$bar ) ); - - $this->assertEquals( 'baz', $foo, 'Data included' ); - $foo = 'Foo'; - - $wgHooks['MediaWikiHooksTest001'][] = array( $i, 'someStatic' ); - - wfRunHooks( 'MediaWikiHooksTest001', array( &$foo, &$bar ) ); - - $this->assertEquals( 'bah', $foo, 'Standard static method' ); - //$foo = 'Foo'; - - unset( $wgHooks['MediaWikiHooksTest001'] ); - - } - - public function testNewStyleHooks() { - $foo = 'Foo'; - $bar = 'Bar'; - - $i = new NothingClass(); - - Hooks::register( 'MediaWikiHooksTest001', array( $i, 'someNonStatic' ) ); - - Hooks::run( 'MediaWikiHooksTest001', array( &$foo, &$bar ) ); - - $this->assertEquals( 'fOO', $foo, 'Standard method' ); - $foo = 'Foo'; - - Hooks::register( 'MediaWikiHooksTest001', $i ); - - Hooks::run( 'MediaWikiHooksTest001', array( &$foo, &$bar ) ); - - $this->assertEquals( 'foo', $foo, 'onEventName style' ); - $foo = 'Foo'; - - Hooks::register( 'MediaWikiHooksTest001', array( $i, 'someNonStaticWithData', 'baz' ) ); - - Hooks::run( 'MediaWikiHooksTest001', array( &$foo, &$bar ) ); - - $this->assertEquals( 'baz', $foo, 'Data included' ); - $foo = 'Foo'; - - Hooks::register( 'MediaWikiHooksTest001', array( $i, 'someStatic' ) ); - - Hooks::run( 'MediaWikiHooksTest001', array( &$foo, &$bar ) ); - - $this->assertEquals( 'bah', $foo, 'Standard static method' ); - $foo = 'Foo'; - } -} - -class NothingClass { - static public function someStatic( &$foo, &$bar ) { - $foo = 'bah'; - return true; - } - - public function someNonStatic( &$foo, &$bar ) { - $foo = 'fOO'; - $bar = 'bAR'; - return true; - } - - public function onMediaWikiHooksTest001( &$foo, &$bar ) { - $foo = 'foo'; - return true; - } - - public function someNonStaticWithData( $foo, &$bar ) { - $bar = $foo; - return true; - } -} diff --git a/tests/phpunit/includes/HtmlTest.php b/tests/phpunit/includes/HtmlTest.php deleted file mode 100644 index 135ebc5a..00000000 --- a/tests/phpunit/includes/HtmlTest.php +++ /dev/null @@ -1,580 +0,0 @@ -getNamespaces(); - self::$oldLanguageCode = $wgLanguageCode; - self::$oldHTML5 = $wgHTML5; - - $wgLanguageCode = 'en'; - $wgContLang = $wgLang = Language::factory( $wgLanguageCode ); - - // Hardcode namespaces during test runs, - // so that html output based on existing namespaces - // can be properly evaluated. - $wgContLang->setNamespaces( array( - -2 => 'Media', - -1 => 'Special', - 0 => '', - 1 => 'Talk', - 2 => 'User', - 3 => 'User_talk', - 4 => 'MyWiki', - 5 => 'MyWiki_Talk', - 6 => 'File', - 7 => 'File_talk', - 8 => 'MediaWiki', - 9 => 'MediaWiki_talk', - 10 => 'Template', - 11 => 'Template_talk', - 14 => 'Category', - 15 => 'Category_talk', - 100 => 'Custom', - 101 => 'Custom_talk', - ) ); - } - - public function tearDown() { - global $wgLang, $wgContLang, $wgLanguageCode, $wgHTML5; - - // Restore globals - $wgContLang->setNamespaces( self::$oldNamespaces ); - $wgLang = self::$oldLang; - $wgContLang = self::$oldContLang; - $wgLanguageCode = self::$oldLanguageCode; - $wgHTML5 = self::$oldHTML5; - } - - /** - * Wrapper to easily set $wgHTML5 = true. - * Original value will be restored after test completion. - * @todo Move to MediaWikiTestCase - */ - public function enableHTML5() { - global $wgHTML5; - $wgHTML5 = true; - } - /** - * Wrapper to easily set $wgHTML5 = false - * Original value will be restored after test completion. - * @todo Move to MediaWikiTestCase - */ - public function disableHTML5() { - global $wgHTML5; - $wgHTML5 = false; - } - - public function testExpandAttributesSkipsNullAndFalse() { - - ### EMPTY ######## - $this->AssertEmpty( - Html::expandAttributes( array( 'foo' => null ) ), - 'skip keys with null value' - ); - $this->AssertEmpty( - Html::expandAttributes( array( 'foo' => false ) ), - 'skip keys with false value' - ); - $this->AssertNotEmpty( - Html::expandAttributes( array( 'foo' => '' ) ), - 'keep keys with an empty string' - ); - } - - public function testExpandAttributesForBooleans() { - global $wgHtml5; - $this->AssertEquals( - '', - Html::expandAttributes( array( 'selected' => false ) ), - 'Boolean attributes do not generates output when value is false' - ); - $this->AssertEquals( - '', - Html::expandAttributes( array( 'selected' => null ) ), - 'Boolean attributes do not generates output when value is null' - ); - - $this->AssertEquals( - $wgHtml5 ? ' selected=""' : ' selected="selected"', - Html::expandAttributes( array( 'selected' => true ) ), - 'Boolean attributes skip value output' - ); - $this->AssertEquals( - $wgHtml5 ? ' selected=""' : ' selected="selected"', - Html::expandAttributes( array( 'selected' ) ), - 'Boolean attributes (ex: selected) do not need a value' - ); - } - - /** - * Test for Html::expandAttributes() - * Please note it output a string prefixed with a space! - */ - public function testExpandAttributesVariousExpansions() { - ### NOT EMPTY #### - $this->AssertEquals( - ' empty_string=""', - Html::expandAttributes( array( 'empty_string' => '' ) ), - 'Value with an empty string' - ); - $this->AssertEquals( - ' key="value"', - Html::expandAttributes( array( 'key' => 'value' ) ), - 'Value is a string' - ); - $this->AssertEquals( - ' one="1"', - Html::expandAttributes( array( 'one' => 1 ) ), - 'Value is a numeric one' - ); - $this->AssertEquals( - ' zero="0"', - Html::expandAttributes( array( 'zero' => 0 ) ), - 'Value is a numeric zero' - ); - } - - /** - * Html::expandAttributes has special features for HTML - * attributes that use space separated lists and also - * allows arrays to be used as values. - */ - public function testExpandAttributesListValueAttributes() { - ### STRING VALUES - $this->AssertEquals( - ' class="redundant spaces here"', - Html::expandAttributes( array( 'class' => ' redundant spaces here ' ) ), - 'Normalization should strip redundant spaces' - ); - $this->AssertEquals( - ' class="foo bar"', - Html::expandAttributes( array( 'class' => 'foo bar foo bar bar' ) ), - 'Normalization should remove duplicates in string-lists' - ); - ### "EMPTY" ARRAY VALUES - $this->AssertEquals( - ' class=""', - Html::expandAttributes( array( 'class' => array() ) ), - 'Value with an empty array' - ); - $this->AssertEquals( - ' class=""', - Html::expandAttributes( array( 'class' => array( null, '', ' ', ' ' ) ) ), - 'Array with null, empty string and spaces' - ); - ### NON-EMPTY ARRAY VALUES - $this->AssertEquals( - ' class="foo bar"', - Html::expandAttributes( array( 'class' => array( - 'foo', - 'bar', - 'foo', - 'bar', - 'bar', - ) ) ), - 'Normalization should remove duplicates in the array' - ); - $this->AssertEquals( - ' class="foo bar"', - Html::expandAttributes( array( 'class' => array( - 'foo bar', - 'bar foo', - 'foo', - 'bar bar', - ) ) ), - 'Normalization should remove duplicates in string-lists in the array' - ); - } - - /** - * Test feature added by r96188, let pass attributes values as - * a PHP array. Restricted to class,rel, accesskey. - */ - function testExpandAttributesSpaceSeparatedAttributesWithBoolean() { - $this->assertEquals( - ' class="booltrue one"', - Html::expandAttributes( array( 'class' => array( - 'booltrue' => true, - 'one' => 1, - - # Method use isset() internally, make sure we do discard - # attributes values which have been assigned well known values - 'emptystring' => '', - 'boolfalse' => false, - 'zero' => 0, - 'null' => null, - ))) - ); - } - - /** - * How do we handle duplicate keys in HTML attributes expansion? - * We could pass a "class" the values: 'GREEN' and array( 'GREEN' => false ) - * The later will take precedence. - * - * Feature added by r96188 - */ - function testValueIsAuthoritativeInSpaceSeparatedAttributesArrays() { - $this->assertEquals( - ' class=""', - Html::expandAttributes( array( 'class' => array( - 'GREEN', - 'GREEN' => false, - 'GREEN', - ))) - ); - } - - function testNamespaceSelector() { - $this->assertEquals( - '', - Html::namespaceSelector(), - 'Basic namespace selector without custom options' - ); - - $this->assertEquals( - ' ' . -'', - Html::namespaceSelector( - array( 'selected' => '2', 'all' => 'all', 'label' => 'Select a namespace:' ), - array( 'name' => 'wpNamespace', 'id' => 'mw-test-namespace' ) - ), - 'Basic namespace selector with custom values' - ); - - $this->assertEquals( - ' ' . -'', - Html::namespaceSelector( - array( 'label' => 'Select a namespace:' ) - ), - 'Basic namespace selector with a custom label but no id attribtue for the ' . "\n" . -'' . "\n" . -'' . "\n" . -'' . "\n" . -'' . "\n" . -'' . "\n" . -'' . "\n" . -'' . "\n" . -'' . "\n" . -'' . "\n" . -'' . "\n" . -'' . "\n" . -'', - Html::namespaceSelector( - array( 'exclude' => array( 0, 1, 3, 100, 101 ) ) - ), - 'Namespace selector namespace filtering.' - ); - } - - function testCanDisableANamespaces() { - $this->assertEquals( -'', - Html::namespaceSelector( array( - 'disable' => array( 0, 1, 2, 3, 4 ) - ) ), - 'Namespace selector namespace disabling' - ); - } - - /** - * @dataProvider providesHtml5InputTypes - */ - function testHtmlElementAcceptsNewHtml5TypesInHtml5Mode( $HTML5InputType ) { - $this->enableHTML5(); - $this->assertEquals( - '', - HTML::element( 'input', array( 'type' => $HTML5InputType ) ), - 'In HTML5, HTML::element() should accept type="' . $HTML5InputType . '"' - ); - } - - /** - * List of input element types values introduced by HTML5 - * Full list at http://www.w3.org/TR/html-markup/input.html - */ - function providesHtml5InputTypes() { - $types = array( - 'datetime', - 'datetime-local', - 'date', - 'month', - 'time', - 'week', - 'number', - 'range', - 'email', - 'url', - 'search', - 'tel', - 'color', - ); - $cases = array(); - foreach( $types as $type ) { - $cases[] = array( $type ); - } - return $cases; - } - - /** - * Test out Html::element drops default value - * @cover Html::dropDefaults - * @dataProvider provideElementsWithAttributesHavingDefaultValues - */ - function testDropDefaults( $expected, $element, $message = '' ) { - $this->enableHTML5(); - $this->assertEquals( $expected, $element, $message ); - } - - function provideElementsWithAttributesHavingDefaultValues() { - # Use cases in a concise format: - # , , [, ] - # Will be mapped to Html::element() - $cases = array(); - - ### Generic cases, match $attribDefault static array - $cases[] = array( '', - 'area', array( 'shape' => 'rect' ) - ); - - $cases[] = array( '', - 'button', array( 'formaction' => 'GET' ) - ); - $cases[] = array( '', - 'button', array( 'formenctype' => 'application/x-www-form-urlencoded' ) - ); - $cases[] = array( '', - 'button', array( 'type' => 'submit' ) - ); - - $cases[] = array( '', - 'canvas', array( 'height' => '150' ) - ); - $cases[] = array( '', - 'canvas', array( 'width' => '300' ) - ); - # Also check with numeric values - $cases[] = array( '', - 'canvas', array( 'height' => 150 ) - ); - $cases[] = array( '', - 'canvas', array( 'width' => 300 ) - ); - - $cases[] = array( '', - 'command', array( 'type' => 'command' ) - ); - - $cases[] = array( '
', - 'form', array( 'action' => 'GET' ) - ); - $cases[] = array( '
', - 'form', array( 'autocomplete' => 'on' ) - ); - $cases[] = array( '
', - 'form', array( 'enctype' => 'application/x-www-form-urlencoded' ) - ); - - $cases[] = array( '', - 'input', array( 'formaction' => 'GET' ) - ); - $cases[] = array( '', - 'input', array( 'type' => 'text' ) - ); - - $cases[] = array( '', - 'keygen', array( 'keytype' => 'rsa' ) - ); - - $cases[] = array( '', - 'link', array( 'media' => 'all' ) - ); - - $cases[] = array( '', - 'menu', array( 'type' => 'list' ) - ); - - $cases[] = array( '', - 'script', array( 'type' => 'text/javascript' ) - ); - - $cases[] = array( '', - 'style', array( 'media' => 'all' ) - ); - $cases[] = array( '', - 'style', array( 'type' => 'text/css' ) - ); - - $cases[] = array( '', - 'textarea', array( 'wrap' => 'soft' ) - ); - - ### SPECIFIC CASES - - # - $cases[] = array( '', - 'link', array( 'type' => 'text/css' ) - ); - - # specific handling - $cases[] = array( '', - 'input', array( 'type' => 'checkbox', 'value' => 'on' ), - 'Default value "on" is stripped of checkboxes', - ); - $cases[] = array( '', - 'input', array( 'type' => 'radio', 'value' => 'on' ), - 'Default value "on" is stripped of radio buttons', - ); - $cases[] = array( '', - 'input', array( 'type' => 'submit', 'value' => 'Submit' ), - 'Default value "Submit" is kept on submit buttons (for possible l10n issues)', - ); - $cases[] = array( '', - 'input', array( 'type' => 'color', 'value' => '' ), - ); - $cases[] = array( '', - 'input', array( 'type' => 'range', 'value' => '' ), - ); - - # ', - 'select', array( 'size' => '4', 'multiple' => true ), - ); - # .. with numeric value - $cases[] = array( '', - 'select', array( 'size' => 4, 'multiple' => true ), - ); - $cases[] = array( '', - 'select', array( 'size' => '1', 'multiple' => false ), - ); - # .. with numeric value - $cases[] = array( '', - 'select', array( 'size' => 1, 'multiple' => false ), - ); - - # Passing an array as value - $cases[] = array( '', - 'a', array( 'class' => array( 'css-class-one', 'css-class-two' ) ), - "dropDefaults accepts values given as an array" - ); - - # FIXME: doDropDefault should remove defaults given in an array - # Expected should be '' - $cases[] = array( '', - 'a', array( 'class' => array( '', '' ) ), - "dropDefaults accepts values given as an array" - ); - - - # Craft the Html elements - $ret = array(); - foreach( $cases as $case ) { - $ret[] = array( - $case[0], - Html::element( $case[1], $case[2] ) - ); - } - return $ret; - } - - public function testFormValidationBlacklist() { - $this->assertEmpty( - Html::expandAttributes( array( 'min' => 1, 'max' => 100, 'pattern' => 'abc', 'required' => true, 'step' => 2 ) ), - 'Blacklist form validation attributes.' - ); - $this->assertEquals( - ' step="any"', - Html::expandAttributes( array( 'min' => 1, 'max' => 100, 'pattern' => 'abc', 'required' => true, 'step' => 'any' ) ), - "Allow special case 'step=\"any\"'." - ); - } - -} diff --git a/tests/phpunit/includes/HttpTest.php b/tests/phpunit/includes/HttpTest.php deleted file mode 100644 index 263383f1..00000000 --- a/tests/phpunit/includes/HttpTest.php +++ /dev/null @@ -1,180 +0,0 @@ -assertEquals( $expected, $ok, $msg ); - } - - function cookieDomains() { - return array( - array( false, "org"), - array( false, ".org"), - array( true, "wikipedia.org"), - array( true, ".wikipedia.org"), - array( false, "co.uk" ), - array( false, ".co.uk" ), - array( false, "gov.uk" ), - array( false, ".gov.uk" ), - array( true, "supermarket.uk" ), - array( false, "uk" ), - array( false, ".uk" ), - array( false, "127.0.0." ), - array( false, "127." ), - array( false, "127.0.0.1." ), - array( true, "127.0.0.1" ), - array( false, "333.0.0.1" ), - array( true, "example.com" ), - array( false, "example.com." ), - array( true, ".example.com" ), - - array( true, ".example.com", "www.example.com" ), - array( false, "example.com", "www.example.com" ), - array( true, "127.0.0.1", "127.0.0.1" ), - array( false, "127.0.0.1", "localhost" ), - ); - } - - /** - * Test Http::isValidURI() - * @bug 27854 : Http::isValidURI is too lax - * @dataProvider provideURI - */ - function testIsValidUri( $expect, $URI, $message = '' ) { - $this->assertEquals( - $expect, - (bool) Http::isValidURI( $URI ), - $message - ); - } - - /** - * Feeds URI to test a long regular expression in Http::isValidURI - */ - function provideURI() { - /** Format: 'boolean expectation', 'URI to test', 'Optional message' */ - return array( - array( false, '¿non sens before!! http://a', 'Allow anything before URI' ), - - # (http|https) - only two schemes allowed - array( true, 'http://www.example.org/' ), - array( true, 'https://www.example.org/' ), - array( true, 'http://www.example.org', 'URI without directory' ), - array( true, 'http://a', 'Short name' ), - array( true, 'http://étoile', 'Allow UTF-8 in hostname' ), # 'étoile' is french for 'star' - array( false, '\\host\directory', 'CIFS share' ), - array( false, 'gopher://host/dir', 'Reject gopher scheme' ), - array( false, 'telnet://host', 'Reject telnet scheme' ), - - # :\/\/ - double slashes - array( false, 'http//example.org', 'Reject missing colon in protocol' ), - array( false, 'http:/example.org', 'Reject missing slash in protocol' ), - array( false, 'http:example.org', 'Must have two slashes' ), - # Following fail since hostname can be made of anything - array( false, 'http:///example.org', 'Must have exactly two slashes, not three' ), - - # (\w+:{0,1}\w*@)? - optional user:pass - array( true, 'http://user@host', 'Username provided' ), - array( true, 'http://user:@host', 'Username provided, no password' ), - array( true, 'http://user:pass@host', 'Username and password provided' ), - - # (\S+) - host part is made of anything not whitespaces - array( false, 'http://!"èèè¿¿¿~~\'', 'hostname is made of any non whitespace' ), - array( false, 'http://exam:ple.org/', 'hostname can not use colons!' ), - - # (:[0-9]+)? - port number - array( true, 'http://example.org:80/' ), - array( true, 'https://example.org:80/' ), - array( true, 'http://example.org:443/' ), - array( true, 'https://example.org:443/' ), - - # Part after the hostname is / or / with something else - array( true, 'http://example/#' ), - array( true, 'http://example/!' ), - array( true, 'http://example/:' ), - array( true, 'http://example/.' ), - array( true, 'http://example/?' ), - array( true, 'http://example/+' ), - array( true, 'http://example/=' ), - array( true, 'http://example/&' ), - array( true, 'http://example/%' ), - array( true, 'http://example/@' ), - array( true, 'http://example/-' ), - array( true, 'http://example//' ), - array( true, 'http://example/&' ), - - # Fragment - array( true, 'http://exam#ple.org', ), # This one is valid, really! - array( true, 'http://example.org:80#anchor' ), - array( true, 'http://example.org/?id#anchor' ), - array( true, 'http://example.org/?#anchor' ), - - array( false, 'http://a ¿non !!sens after', 'Allow anything after URI' ), - ); - } - - /** - * Warning: - * - * These tests are for code that makes use of an artifact of how CURL - * handles header reporting on redirect pages, and will need to be - * rewritten when bug 29232 is taken care of (high-level handling of - * HTTP redirects). - */ - function testRelativeRedirections() { - $h = new MWHttpRequestTester( 'http://oldsite/file.ext' ); - # Forge a Location header - $h->setRespHeaders( 'location', array( - 'http://newsite/file.ext', - '/newfile.ext', - ) - ); - # Verify we correctly fix the Location - $this->assertEquals( - 'http://newsite/newfile.ext', - $h->getFinalUrl(), - "Relative file path Location: interpreted as full URL" - ); - - $h->setRespHeaders( 'location', array( - 'https://oldsite/file.ext' - ) - ); - $this->assertEquals( - 'https://oldsite/file.ext', - $h->getFinalUrl(), - "Location to the HTTPS version of the site" - ); - - $h->setRespHeaders( 'location', array( - '/anotherfile.ext', - 'http://anotherfile/hoster.ext', - 'https://anotherfile/hoster.ext' - ) - ); - $this->assertEquals( - 'https://anotherfile/hoster.ext', - $h->getFinalUrl( "Relative file path Location: should keep the latest host and scheme!") - ); - } -} - -/** - * Class to let us overwrite MWHttpREquest respHeaders variable - */ -class MWHttpRequestTester extends MWHttpRequest { - function setRespHeaders( $name, $value ) { - $this->respHeaders[$name] = $value ; - } -} diff --git a/tests/phpunit/includes/IPTest.php b/tests/phpunit/includes/IPTest.php deleted file mode 100644 index f50b2fe9..00000000 --- a/tests/phpunit/includes/IPTest.php +++ /dev/null @@ -1,542 +0,0 @@ -assertFalse( IP::isIPAddress( false ), 'Boolean false is not an IP' ); - $this->assertFalse( IP::isIPAddress( true ), 'Boolean true is not an IP' ); - $this->assertFalse( IP::isIPAddress( "" ), 'Empty string is not an IP' ); - $this->assertFalse( IP::isIPAddress( 'abc' ), 'Garbage IP string' ); - $this->assertFalse( IP::isIPAddress( ':' ), 'Single ":" is not an IP' ); - $this->assertFalse( IP::isIPAddress( '2001:0DB8::A:1::1'), 'IPv6 with a double :: occurrence' ); - $this->assertFalse( IP::isIPAddress( '2001:0DB8::A:1::'), 'IPv6 with a double :: occurrence, last at end' ); - $this->assertFalse( IP::isIPAddress( '::2001:0DB8::5:1'), 'IPv6 with a double :: occurrence, firt at beginning' ); - $this->assertFalse( IP::isIPAddress( '124.24.52' ), 'IPv4 not enough quads' ); - $this->assertFalse( IP::isIPAddress( '24.324.52.13' ), 'IPv4 out of range' ); - $this->assertFalse( IP::isIPAddress( '.24.52.13' ), 'IPv4 starts with period' ); - $this->assertFalse( IP::isIPAddress( 'fc:100:300' ), 'IPv6 with only 3 words' ); - - $this->assertTrue( IP::isIPAddress( '::' ), 'RFC 4291 IPv6 Unspecified Address' ); - $this->assertTrue( IP::isIPAddress( '::1' ), 'RFC 4291 IPv6 Loopback Address' ); - $this->assertTrue( IP::isIPAddress( '74.24.52.13/20', 'IPv4 range' ) ); - $this->assertTrue( IP::isIPAddress( 'fc:100:a:d:1:e:ac:0/24' ), 'IPv6 range' ); - $this->assertTrue( IP::isIPAddress( 'fc::100:a:d:1:e:ac/96' ), 'IPv6 range with "::"' ); - - $validIPs = array( 'fc:100::', 'fc:100:a:d:1:e:ac::', 'fc::100', '::fc:100:a:d:1:e:ac', - '::fc', 'fc::100:a:d:1:e:ac', 'fc:100:a:d:1:e:ac:0', '124.24.52.13', '1.24.52.13' ); - foreach ( $validIPs as $ip ) { - $this->assertTrue( IP::isIPAddress( $ip ), "$ip is a valid IP address" ); - } - } - - /** - * @covers IP::isIPv6 - */ - public function testisIPv6() { - $this->assertFalse( IP::isIPv6( ':fc:100::' ), 'IPv6 starting with lone ":"' ); - $this->assertFalse( IP::isIPv6( 'fc:100:::' ), 'IPv6 ending with a ":::"' ); - $this->assertFalse( IP::isIPv6( 'fc:300' ), 'IPv6 with only 2 words' ); - $this->assertFalse( IP::isIPv6( 'fc:100:300' ), 'IPv6 with only 3 words' ); - - $this->assertTrue( IP::isIPv6( 'fc:100::' ) ); - $this->assertTrue( IP::isIPv6( 'fc:100:a::' ) ); - $this->assertTrue( IP::isIPv6( 'fc:100:a:d::' ) ); - $this->assertTrue( IP::isIPv6( 'fc:100:a:d:1::' ) ); - $this->assertTrue( IP::isIPv6( 'fc:100:a:d:1:e::' ) ); - $this->assertTrue( IP::isIPv6( 'fc:100:a:d:1:e:ac::' ) ); - - $this->assertFalse( IP::isIPv6( 'fc:100:a:d:1:e:ac:0::' ), 'IPv6 with 8 words ending with "::"' ); - $this->assertFalse( IP::isIPv6( 'fc:100:a:d:1:e:ac:0:1::' ), 'IPv6 with 9 words ending with "::"' ); - - $this->assertFalse( IP::isIPv6( ':::' ) ); - $this->assertFalse( IP::isIPv6( '::0:' ), 'IPv6 ending in a lone ":"' ); - - $this->assertTrue( IP::isIPv6( '::' ), 'IPv6 zero address' ); - $this->assertTrue( IP::isIPv6( '::0' ) ); - $this->assertTrue( IP::isIPv6( '::fc' ) ); - $this->assertTrue( IP::isIPv6( '::fc:100' ) ); - $this->assertTrue( IP::isIPv6( '::fc:100:a' ) ); - $this->assertTrue( IP::isIPv6( '::fc:100:a:d' ) ); - $this->assertTrue( IP::isIPv6( '::fc:100:a:d:1' ) ); - $this->assertTrue( IP::isIPv6( '::fc:100:a:d:1:e' ) ); - $this->assertTrue( IP::isIPv6( '::fc:100:a:d:1:e:ac' ) ); - - $this->assertFalse( IP::isIPv6( '::fc:100:a:d:1:e:ac:0' ), 'IPv6 with "::" and 8 words' ); - $this->assertFalse( IP::isIPv6( '::fc:100:a:d:1:e:ac:0:1' ), 'IPv6 with 9 words' ); - - $this->assertFalse( IP::isIPv6( ':fc::100' ), 'IPv6 starting with lone ":"' ); - $this->assertFalse( IP::isIPv6( 'fc::100:' ), 'IPv6 ending with lone ":"' ); - $this->assertFalse( IP::isIPv6( 'fc:::100' ), 'IPv6 with ":::" in the middle' ); - - $this->assertTrue( IP::isIPv6( 'fc::100' ), 'IPv6 with "::" and 2 words' ); - $this->assertTrue( IP::isIPv6( 'fc::100:a' ), 'IPv6 with "::" and 3 words' ); - $this->assertTrue( IP::isIPv6( 'fc::100:a:d', 'IPv6 with "::" and 4 words' ) ); - $this->assertTrue( IP::isIPv6( 'fc::100:a:d:1' ), 'IPv6 with "::" and 5 words' ); - $this->assertTrue( IP::isIPv6( 'fc::100:a:d:1:e' ), 'IPv6 with "::" and 6 words' ); - $this->assertTrue( IP::isIPv6( 'fc::100:a:d:1:e:ac' ), 'IPv6 with "::" and 7 words' ); - $this->assertTrue( IP::isIPv6( '2001::df'), 'IPv6 with "::" and 2 words' ); - $this->assertTrue( IP::isIPv6( '2001:5c0:1400:a::df'), 'IPv6 with "::" and 5 words' ); - $this->assertTrue( IP::isIPv6( '2001:5c0:1400:a::df:2'), 'IPv6 with "::" and 6 words' ); - - $this->assertFalse( IP::isIPv6( 'fc::100:a:d:1:e:ac:0' ), 'IPv6 with "::" and 8 words' ); - $this->assertFalse( IP::isIPv6( 'fc::100:a:d:1:e:ac:0:1' ), 'IPv6 with 9 words' ); - - $this->assertTrue( IP::isIPv6( 'fc:100:a:d:1:e:ac:0' ) ); - } - - /** - * @covers IP::isIPv4 - */ - public function testisIPv4() { - $this->assertFalse( IP::isIPv4( false ), 'Boolean false is not an IP' ); - $this->assertFalse( IP::isIPv4( true ), 'Boolean true is not an IP' ); - $this->assertFalse( IP::isIPv4( "" ), 'Empty string is not an IP' ); - $this->assertFalse( IP::isIPv4( 'abc' ) ); - $this->assertFalse( IP::isIPv4( ':' ) ); - $this->assertFalse( IP::isIPv4( '124.24.52' ), 'IPv4 not enough quads' ); - $this->assertFalse( IP::isIPv4( '24.324.52.13' ), 'IPv4 out of range' ); - $this->assertFalse( IP::isIPv4( '.24.52.13' ), 'IPv4 starts with period' ); - - $this->assertTrue( IP::isIPv4( '124.24.52.13' ) ); - $this->assertTrue( IP::isIPv4( '1.24.52.13' ) ); - $this->assertTrue( IP::isIPv4( '74.24.52.13/20', 'IPv4 range' ) ); - } - - /** - * @covers IP::isValid - */ - public function testValidIPs() { - foreach ( range( 0, 255 ) as $i ) { - $a = sprintf( "%03d", $i ); - $b = sprintf( "%02d", $i ); - $c = sprintf( "%01d", $i ); - foreach ( array_unique( array( $a, $b, $c ) ) as $f ) { - $ip = "$f.$f.$f.$f"; - $this->assertTrue( IP::isValid( $ip ) , "$ip is a valid IPv4 address" ); - } - } - foreach ( range( 0x0, 0xFFFF, 0xF ) as $i ) { - $a = sprintf( "%04x", $i ); - $b = sprintf( "%03x", $i ); - $c = sprintf( "%02x", $i ); - foreach ( array_unique( array( $a, $b, $c ) ) as $f ) { - $ip = "$f:$f:$f:$f:$f:$f:$f:$f"; - $this->assertTrue( IP::isValid( $ip ) , "$ip is a valid IPv6 address" ); - } - } - // test with some abbreviations - $this->assertFalse( IP::isValid( ':fc:100::' ), 'IPv6 starting with lone ":"' ); - $this->assertFalse( IP::isValid( 'fc:100:::' ), 'IPv6 ending with a ":::"' ); - $this->assertFalse( IP::isValid( 'fc:300' ), 'IPv6 with only 2 words' ); - $this->assertFalse( IP::isValid( 'fc:100:300' ), 'IPv6 with only 3 words' ); - - $this->assertTrue( IP::isValid( 'fc:100::' ) ); - $this->assertTrue( IP::isValid( 'fc:100:a:d:1:e::' ) ); - $this->assertTrue( IP::isValid( 'fc:100:a:d:1:e:ac::' ) ); - - $this->assertTrue( IP::isValid( 'fc::100' ), 'IPv6 with "::" and 2 words' ); - $this->assertTrue( IP::isValid( 'fc::100:a' ), 'IPv6 with "::" and 3 words' ); - $this->assertTrue( IP::isValid( '2001::df'), 'IPv6 with "::" and 2 words' ); - $this->assertTrue( IP::isValid( '2001:5c0:1400:a::df'), 'IPv6 with "::" and 5 words' ); - $this->assertTrue( IP::isValid( '2001:5c0:1400:a::df:2'), 'IPv6 with "::" and 6 words' ); - $this->assertTrue( IP::isValid( 'fc::100:a:d:1' ), 'IPv6 with "::" and 5 words' ); - $this->assertTrue( IP::isValid( 'fc::100:a:d:1:e:ac' ), 'IPv6 with "::" and 7 words' ); - - $this->assertFalse( IP::isValid( 'fc:100:a:d:1:e:ac:0::' ), 'IPv6 with 8 words ending with "::"' ); - $this->assertFalse( IP::isValid( 'fc:100:a:d:1:e:ac:0:1::' ), 'IPv6 with 9 words ending with "::"' ); - } - - /** - * @covers IP::isValid - */ - public function testInvalidIPs() { - // Out of range... - foreach ( range( 256, 999 ) as $i ) { - $a = sprintf( "%03d", $i ); - $b = sprintf( "%02d", $i ); - $c = sprintf( "%01d", $i ); - foreach ( array_unique( array( $a, $b, $c ) ) as $f ) { - $ip = "$f.$f.$f.$f"; - $this->assertFalse( IP::isValid( $ip ), "$ip is not a valid IPv4 address" ); - } - } - foreach ( range( 'g', 'z' ) as $i ) { - $a = sprintf( "%04s", $i ); - $b = sprintf( "%03s", $i ); - $c = sprintf( "%02s", $i ); - foreach ( array_unique( array( $a, $b, $c ) ) as $f ) { - $ip = "$f:$f:$f:$f:$f:$f:$f:$f"; - $this->assertFalse( IP::isValid( $ip ) , "$ip is not a valid IPv6 address" ); - } - } - // Have CIDR - $ipCIDRs = array( - '212.35.31.121/32', - '212.35.31.121/18', - '212.35.31.121/24', - '::ff:d:321:5/96', - 'ff::d3:321:5/116', - 'c:ff:12:1:ea:d:321:5/120', - ); - foreach ( $ipCIDRs as $i ) { - $this->assertFalse( IP::isValid( $i ), - "$i is an invalid IP address because it is a block" ); - } - // Incomplete/garbage - $invalid = array( - 'www.xn--var-xla.net', - '216.17.184.G', - '216.17.184.1.', - '216.17.184', - '216.17.184.', - '256.17.184.1' - ); - foreach ( $invalid as $i ) { - $this->assertFalse( IP::isValid( $i ), "$i is an invalid IP address" ); - } - } - - /** - * @covers IP::isValidBlock - */ - public function testValidBlocks() { - $valid = array( - '116.17.184.5/32', - '0.17.184.5/30', - '16.17.184.1/24', - '30.242.52.14/1', - '10.232.52.13/8', - '30.242.52.14/0', - '::e:f:2001/96', - '::c:f:2001/128', - '::10:f:2001/70', - '::fe:f:2001/1', - '::6d:f:2001/8', - '::fe:f:2001/0', - ); - foreach ( $valid as $i ) { - $this->assertTrue( IP::isValidBlock( $i ), "$i is a valid IP block" ); - } - } - - /** - * @covers IP::isValidBlock - */ - public function testInvalidBlocks() { - $invalid = array( - '116.17.184.5/33', - '0.17.184.5/130', - '16.17.184.1/-1', - '10.232.52.13/*', - '7.232.52.13/ab', - '11.232.52.13/', - '::e:f:2001/129', - '::c:f:2001/228', - '::10:f:2001/-1', - '::6d:f:2001/*', - '::86:f:2001/ab', - '::23:f:2001/', - ); - foreach ( $invalid as $i ) { - $this->assertFalse( IP::isValidBlock( $i ), "$i is not a valid IP block" ); - } - } - - /** - * Improve IP::sanitizeIP() code coverage - * @todo Most probably incomplete - */ - public function testSanitizeIP() { - $this->assertNull( IP::sanitizeIP('') ); - $this->assertNull( IP::sanitizeIP(' ') ); - } - - /** - * test wrapper around ip2long which might return -1 or false depending on PHP version - * @covers IP::toUnsigned - */ - public function testip2longWrapper() { - // @todo FIXME: Add more tests ? - $this->assertEquals( pow(2,32) - 1, IP::toUnsigned( '255.255.255.255' )); - $i = 'IN.VA.LI.D'; - $this->assertFalse( IP::toUnSigned( $i ) ); - } - - /** - * @covers IP::isPublic - */ - public function testPrivateIPs() { - $private = array( 'fc00::3', 'fc00::ff', '::1', '10.0.0.1', '172.16.0.1', '192.168.0.1' ); - foreach ( $private as $p ) { - $this->assertFalse( IP::isPublic( $p ), "$p is not a public IP address" ); - } - $public = array( '2001:5c0:1000:a::133', 'fc::3', '00FC::' ); - foreach ( $public as $p ) { - $this->assertTrue( IP::isPublic( $p ), "$p is a public IP address" ); - } - } - - // Private wrapper used to test CIDR Parsing. - private function assertFalseCIDR( $CIDR, $msg='' ) { - $ff = array( false, false ); - $this->assertEquals( $ff, IP::parseCIDR( $CIDR ), $msg ); - } - - // Private wrapper to test network shifting using only dot notation - private function assertNet( $expected, $CIDR ) { - $parse = IP::parseCIDR( $CIDR ); - $this->assertEquals( $expected, long2ip( $parse[0] ), "network shifting $CIDR" ); - } - - /** - * @covers IP::hexToQuad - */ - public function testHexToQuad() { - $this->assertEquals( '0.0.0.1' , IP::hexToQuad( '00000001' ) ); - $this->assertEquals( '255.0.0.0' , IP::hexToQuad( 'FF000000' ) ); - $this->assertEquals( '255.255.255.255', IP::hexToQuad( 'FFFFFFFF' ) ); - $this->assertEquals( '10.188.222.255' , IP::hexToQuad( '0ABCDEFF' ) ); - // hex not left-padded... - $this->assertEquals( '0.0.0.0' , IP::hexToQuad( '0' ) ); - $this->assertEquals( '0.0.0.1' , IP::hexToQuad( '1' ) ); - $this->assertEquals( '0.0.0.255' , IP::hexToQuad( 'FF' ) ); - $this->assertEquals( '0.0.255.0' , IP::hexToQuad( 'FF00' ) ); - } - - /** - * @covers IP::hexToOctet - */ - public function testHexToOctet() { - $this->assertEquals( '0:0:0:0:0:0:0:1', - IP::hexToOctet( '00000000000000000000000000000001' ) ); - $this->assertEquals( '0:0:0:0:0:0:FF:3', - IP::hexToOctet( '00000000000000000000000000FF0003' ) ); - $this->assertEquals( '0:0:0:0:0:0:FF00:6', - IP::hexToOctet( '000000000000000000000000FF000006' ) ); - $this->assertEquals( '0:0:0:0:0:0:FCCF:FAFF', - IP::hexToOctet( '000000000000000000000000FCCFFAFF' ) ); - $this->assertEquals( 'FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF', - IP::hexToOctet( 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' ) ); - // hex not left-padded... - $this->assertEquals( '0:0:0:0:0:0:0:0' , IP::hexToOctet( '0' ) ); - $this->assertEquals( '0:0:0:0:0:0:0:1' , IP::hexToOctet( '1' ) ); - $this->assertEquals( '0:0:0:0:0:0:0:FF' , IP::hexToOctet( 'FF' ) ); - $this->assertEquals( '0:0:0:0:0:0:0:FFD0' , IP::hexToOctet( 'FFD0' ) ); - $this->assertEquals( '0:0:0:0:0:0:FA00:0' , IP::hexToOctet( 'FA000000' ) ); - $this->assertEquals( '0:0:0:0:0:0:FCCF:FAFF', IP::hexToOctet( 'FCCFFAFF' ) ); - } - - /** - * IP::parseCIDR() returns an array containing a signed IP address - * representing the network mask and the bit mask. - * @covers IP::parseCIDR - */ - function testCIDRParsing() { - $this->assertFalseCIDR( '192.0.2.0' , "missing mask" ); - $this->assertFalseCIDR( '192.0.2.0/', "missing bitmask" ); - - // Verify if statement - $this->assertFalseCIDR( '256.0.0.0/32', "invalid net" ); - $this->assertFalseCIDR( '192.0.2.0/AA', "mask not numeric" ); - $this->assertFalseCIDR( '192.0.2.0/-1', "mask < 0" ); - $this->assertFalseCIDR( '192.0.2.0/33', "mask > 32" ); - - // Check internal logic - # 0 mask always result in array(0,0) - $this->assertEquals( array( 0, 0 ), IP::parseCIDR('192.0.0.2/0') ); - $this->assertEquals( array( 0, 0 ), IP::parseCIDR('0.0.0.0/0') ); - $this->assertEquals( array( 0, 0 ), IP::parseCIDR('255.255.255.255/0') ); - - // @todo FIXME: Add more tests. - - # This part test network shifting - $this->assertNet( '192.0.0.0' , '192.0.0.2/24' ); - $this->assertNet( '192.168.5.0', '192.168.5.13/24'); - $this->assertNet( '10.0.0.160' , '10.0.0.161/28' ); - $this->assertNet( '10.0.0.0' , '10.0.0.3/28' ); - $this->assertNet( '10.0.0.0' , '10.0.0.3/30' ); - $this->assertNet( '10.0.0.4' , '10.0.0.4/30' ); - $this->assertNet( '172.17.32.0', '172.17.35.48/21' ); - $this->assertNet( '10.128.0.0' , '10.135.0.0/9' ); - $this->assertNet( '134.0.0.0' , '134.0.5.1/8' ); - } - - - /** - * @covers IP::canonicalize - */ - public function testIPCanonicalizeOnValidIp() { - $this->assertEquals( '192.0.2.152', IP::canonicalize( '192.0.2.152' ), - 'Canonicalization of a valid IP returns it unchanged' ); - } - - /** - * @covers IP::canonicalize - */ - public function testIPCanonicalizeMappedAddress() { - $this->assertEquals( - '192.0.2.152', - IP::canonicalize( '::ffff:192.0.2.152' ) - ); - $this->assertEquals( - '192.0.2.152', - IP::canonicalize( '::192.0.2.152' ) - ); - } - - /** - * Issues there are most probably from IP::toHex() or IP::parseRange() - * @covers IP::isInRange - * @dataProvider provideIPsAndRanges - */ - public function testIPIsInRange( $expected, $addr, $range, $message = '' ) { - $this->assertEquals( - $expected, - IP::isInRange( $addr, $range ), - $message - ); - } - - /** Provider for testIPIsInRange() */ - function provideIPsAndRanges() { - # Format: (expected boolean, address, range, optional message) - return array( - # IPv4 - array( true , '192.0.2.0' , '192.0.2.0/24', 'Network address' ), - array( true , '192.0.2.77' , '192.0.2.0/24', 'Simple address' ), - array( true , '192.0.2.255' , '192.0.2.0/24', 'Broadcast address' ), - - array( false, '0.0.0.0' , '192.0.2.0/24' ), - array( false, '255.255.255' , '192.0.2.0/24' ), - - # IPv6 - array( false, '::1' , '2001:DB8::/32' ), - array( false, '::' , '2001:DB8::/32' ), - array( false, 'FE80::1', '2001:DB8::/32' ), - - array( true , '2001:DB8::' , '2001:DB8::/32' ), - array( true , '2001:0DB8::' , '2001:DB8::/32' ), - array( true , '2001:DB8::1' , '2001:DB8::/32' ), - array( true , '2001:0DB8::1', '2001:DB8::/32' ), - array( true , '2001:0DB8:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF', - '2001:DB8::/32' ), - - array( false, '2001:0DB8:F::', '2001:DB8::/96' ), - ); - } - - /** - * Test for IP::splitHostAndPort(). - * @dataProvider provideSplitHostAndPort - */ - function testSplitHostAndPort( $expected, $input, $description ) { - $this->assertEquals( $expected, IP::splitHostAndPort( $input ), $description ); - } - - /** - * Provider for IP::splitHostAndPort() - */ - function provideSplitHostAndPort() { - return array( - array( false, '[', 'Unclosed square bracket' ), - array( false, '[::', 'Unclosed square bracket 2' ), - array( array( '::', false ), '::', 'Bare IPv6 0' ), - array( array( '::1', false ), '::1', 'Bare IPv6 1' ), - array( array( '::', false ), '[::]', 'Bracketed IPv6 0' ), - array( array( '::1', false ), '[::1]', 'Bracketed IPv6 1' ), - array( array( '::1', 80 ), '[::1]:80', 'Bracketed IPv6 with port' ), - array( false, '::x', 'Double colon but no IPv6' ), - array( array( 'x', 80 ), 'x:80', 'Hostname and port' ), - array( false, 'x:x', 'Hostname and invalid port' ), - array( array( 'x', false ), 'x', 'Plain hostname' ) - ); - } - - /** - * Test for IP::combineHostAndPort() - * @dataProvider provideCombineHostAndPort - */ - function testCombineHostAndPort( $expected, $input, $description ) { - list( $host, $port, $defaultPort ) = $input; - $this->assertEquals( - $expected, - IP::combineHostAndPort( $host, $port, $defaultPort ), - $description ); - } - - /** - * Provider for IP::combineHostAndPort() - */ - function provideCombineHostAndPort() { - return array( - array( '[::1]', array( '::1', 2, 2 ), 'IPv6 default port' ), - array( '[::1]:2', array( '::1', 2, 3 ), 'IPv6 non-default port' ), - array( 'x', array( 'x', 2, 2 ), 'Normal default port' ), - array( 'x:2', array( 'x', 2, 3 ), 'Normal non-default port' ), - ); - } - - /** - * Test for IP::sanitizeRange() - * @dataProvider provideIPCIDRs - */ - function testSanitizeRange( $input, $expected, $description ) { - $this->assertEquals( $expected, IP::sanitizeRange( $input ), $description ); - } - - /** - * Provider for IP::testSanitizeRange() - */ - function provideIPCIDRs() { - return array( - array( '35.56.31.252/16', '35.56.0.0/16', 'IPv4 range' ), - array( '135.16.21.252/24', '135.16.21.0/24', 'IPv4 range' ), - array( '5.36.71.252/32', '5.36.71.252/32', 'IPv4 silly range' ), - array( '5.36.71.252', '5.36.71.252', 'IPv4 non-range' ), - array( '0:1:2:3:4:c5:f6:7/96', '0:1:2:3:4:C5:0:0/96', 'IPv6 range' ), - array( '0:1:2:3:4:5:6:7/120', '0:1:2:3:4:5:6:0/120', 'IPv6 range' ), - array( '0:e1:2:3:4:5:e6:7/128', '0:E1:2:3:4:5:E6:7/128', 'IPv6 silly range' ), - array( '0:c1:A2:3:4:5:c6:7', '0:C1:A2:3:4:5:C6:7', 'IPv6 non range' ), - ); - } - - /** - * Test for IP::prettifyIP() - * @dataProvider provideIPsToPrettify - */ - function testPrettifyIP( $ip, $prettified ) { - $this->assertEquals( $prettified, IP::prettifyIP( $ip ), "Prettify of $ip" ); - } - - /** - * Provider for IP::testPrettifyIP() - */ - function provideIPsToPrettify() { - return array( - array( '0:0:0:0:0:0:0:0', '::' ), - array( '0:0:0::0:0:0', '::' ), - array( '0:0:0:1:0:0:0:0', '0:0:0:1::' ), - array( '0:0::f', '::f' ), - array( '0::0:0:0:33:fef:b', '::33:fef:b' ), - array( '3f:535:0:0:0:0:e:fbb', '3f:535::e:fbb' ), - array( '0:0:fef:0:0:0:e:fbb', '0:0:fef::e:fbb' ), - array( 'abbc:2004::0:0:0:0', 'abbc:2004::' ), - array( 'cebc:2004:f:0:0:0:0:0', 'cebc:2004:f::' ), - array( '0:0:0:0:0:0:0:0/16', '::/16' ), - array( '0:0:0::0:0:0/64', '::/64' ), - array( '0:0::f/52', '::f/52' ), - array( '::0:0:33:fef:b/52', '::33:fef:b/52' ), - array( '3f:535:0:0:0:0:e:fbb/48', '3f:535::e:fbb/48' ), - array( '0:0:fef:0:0:0:e:fbb/96', '0:0:fef::e:fbb/96' ), - array( 'abbc:2004:0:0::0:0/40', 'abbc:2004::/40' ), - array( 'aebc:2004:f:0:0:0:0:0/80', 'aebc:2004:f::/80' ), - ); - } -} diff --git a/tests/phpunit/includes/JsonTest.php b/tests/phpunit/includes/JsonTest.php deleted file mode 100644 index 75dd18d5..00000000 --- a/tests/phpunit/includes/JsonTest.php +++ /dev/null @@ -1,33 +0,0 @@ -assertNotEquals( - '\ud840\udc00', - strtolower( FormatJson::encode( "\xf0\xa0\x80\x80" ) ), - 'Test encoding an broken json_encode character (U+20000)' - ); - - - } - - function testDecodeVarTypes() { - - $this->assertInternalType( - 'object', - FormatJson::decode( '{"Name": "Cheeso", "Rank": 7}' ), - 'Default to object' - ); - - $this->assertInternalType( - 'array', - FormatJson::decode( '{"Name": "Cheeso", "Rank": 7}', true ), - 'Optional array' - ); - - } - -} - diff --git a/tests/phpunit/includes/LanguageConverterTest.php b/tests/phpunit/includes/LanguageConverterTest.php deleted file mode 100644 index baf28b07..00000000 --- a/tests/phpunit/includes/LanguageConverterTest.php +++ /dev/null @@ -1,130 +0,0 @@ -lang = new LanguageToTest(); - $this->lc = new TestConverter( $this->lang, 'tg', - array( 'tg', 'tg-latn' ) ); - } - - function tearDown() { - global $wgMemc; - unset( $wgMemc ); - unset( $this->lc ); - unset( $this->lang ); - parent::tearDown(); - } - - function testGetPreferredVariantDefaults() { - $this->assertEquals( 'tg', $this->lc->getPreferredVariant() ); - } - - function testGetPreferredVariantHeaders() { - global $wgRequest; - $wgRequest->setHeader( 'Accept-Language', 'tg-latn' ); - - $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant() ); - } - - function testGetPreferredVariantHeaderWeight() { - global $wgRequest; - $wgRequest->setHeader( 'Accept-Language', 'tg;q=1' ); - - $this->assertEquals( 'tg', $this->lc->getPreferredVariant() ); - } - - function testGetPreferredVariantHeaderWeight2() { - global $wgRequest; - $wgRequest->setHeader( 'Accept-Language', 'tg-latn;q=1' ); - - $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant() ); - } - - function testGetPreferredVariantHeaderMulti() { - global $wgRequest; - $wgRequest->setHeader( 'Accept-Language', 'en, tg-latn;q=1' ); - - $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant() ); - } - - function testGetPreferredVariantUserOption() { - global $wgUser; - - $wgUser = new User; - $wgUser->load(); // from 'defaults' - $wgUser->mId = 1; - $wgUser->mDataLoaded = true; - $wgUser->mOptionsLoaded = true; - $wgUser->setOption( 'variant', 'tg-latn' ); - - $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant() ); - } - - function testGetPreferredVariantHeaderUserVsUrl() { - global $wgRequest, $wgUser, $wgContLang; - - $wgContLang = Language::factory( 'tg-latn' ); - $wgRequest->setVal( 'variant', 'tg' ); - $wgUser = User::newFromId( "admin" ); - $wgUser->setId( 1 ); - $wgUser->mFrom = 'defaults'; - $wgUser->mOptionsLoaded = true; - $wgUser->setOption( 'variant', 'tg-latn' ); // The user's data is ignored - // because the variant is set in the URL. - $this->assertEquals( 'tg', $this->lc->getPreferredVariant() ); - } - - - function testGetPreferredVariantDefaultLanguageVariant() { - global $wgDefaultLanguageVariant; - - $wgDefaultLanguageVariant = 'tg-latn'; - $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant() ); - } - - function testGetPreferredVariantDefaultLanguageVsUrlVariant() { - global $wgDefaultLanguageVariant, $wgRequest, $wgContLang; - - $wgContLang = Language::factory( 'tg-latn' ); - $wgDefaultLanguageVariant = 'tg'; - $wgRequest->setVal( 'variant', null ); - $this->assertEquals( 'tg', $this->lc->getPreferredVariant() ); - } -} - -/** - * Test converter (from Tajiki to latin orthography) - */ -class TestConverter extends LanguageConverter { - private $table = array( - 'б' => 'b', - 'в' => 'v', - 'г' => 'g', - ); - - function loadDefaultTables() { - $this->mTables = array( - 'tg-latn' => new ReplacementArray( $this->table ), - 'tg' => new ReplacementArray() - ); - } - -} - -class LanguageToTest extends Language { - function __construct() { - parent::__construct(); - $variants = array( 'tg', 'tg-latn' ); - $this->mConverter = new TestConverter( $this, 'tg', $variants ); - } -} diff --git a/tests/phpunit/includes/LicensesTest.php b/tests/phpunit/includes/LicensesTest.php deleted file mode 100644 index e467f3cd..00000000 --- a/tests/phpunit/includes/LicensesTest.php +++ /dev/null @@ -1,22 +0,0 @@ - 'FooField', - 'type' => 'select', - 'section' => 'description', - 'id' => 'wpLicense', - 'label' => 'A label text', # Note can't test label-message because $wgOut is not defined - 'name' => 'AnotherName', - 'licenses' => $str, - ) ); - $this->assertThat( $lc, $this->isInstanceOf( 'Licenses' ) ); - } -} diff --git a/tests/phpunit/includes/LinksUpdateTest.php b/tests/phpunit/includes/LinksUpdateTest.php deleted file mode 100644 index 49462001..00000000 --- a/tests/phpunit/includes/LinksUpdateTest.php +++ /dev/null @@ -1,154 +0,0 @@ -tablesUsed = array_merge ( $this->tablesUsed, - array( 'interwiki', - - 'page_props', - 'pagelinks', - 'categorylinks', - 'langlinks', - 'externallinks', - 'imagelinks', - 'templatelinks', - 'iwlinks' ) ); - } - - function setUp() { - $dbw = wfGetDB( DB_MASTER ); - $dbw->replace( 'interwiki', - array('iw_prefix'), - array( 'iw_prefix' => 'linksupdatetest', - 'iw_url' => 'http://testing.com/wiki/$1', - 'iw_api' => 'http://testing.com/w/api.php', - 'iw_local' => 0, - 'iw_trans' => 0, - 'iw_wikiid' => 'linksupdatetest', - ) ); - } - - protected function makeTitleAndParserOutput( $name, $id ) { - $t = Title::newFromText( $name ); - $t->mArticleID = $id; # XXX: this is fugly - - $po = new ParserOutput(); - $po->setTitleText( $t->getPrefixedText() ); - - return array( $t, $po ); - } - - public function testUpdate_pagelinks() { - list( $t, $po ) = $this->makeTitleAndParserOutput( "Testing", 111 ); - - $po->addLink( Title::newFromText( "Foo" ) ); - $po->addLink( Title::newFromText( "Special:Foo" ) ); // special namespace should be ignored - $po->addLink( Title::newFromText( "linksupdatetest:Foo" ) ); // interwiki link should be ignored - $po->addLink( Title::newFromText( "#Foo" ) ); // hash link should be ignored - - $this->assertLinksUpdate( $t, $po, 'pagelinks', 'pl_namespace, pl_title', 'pl_from = 111', array( - array( NS_MAIN, 'Foo' ), - ) ); - - $po = new ParserOutput(); - $po->setTitleText( $t->getPrefixedText() ); - - $po->addLink( Title::newFromText( "Bar" ) ); - - $this->assertLinksUpdate( $t, $po, 'pagelinks', 'pl_namespace, pl_title', 'pl_from = 111', array( - array( NS_MAIN, 'Bar' ), - ) ); - } - - public function testUpdate_externallinks() { - list( $t, $po ) = $this->makeTitleAndParserOutput( "Testing", 111 ); - - $po->addExternalLink( "http://testing.com/wiki/Foo" ); - - $this->assertLinksUpdate( $t, $po, 'externallinks', 'el_to, el_index', 'el_from = 111', array( - array( 'http://testing.com/wiki/Foo', 'http://com.testing./wiki/Foo' ), - ) ); - } - - public function testUpdate_categorylinks() { - list( $t, $po ) = $this->makeTitleAndParserOutput( "Testing", 111 ); - - $po->addCategory( "Foo", "FOO" ); - - $this->assertLinksUpdate( $t, $po, 'categorylinks', 'cl_to, cl_sortkey', 'cl_from = 111', array( - array( 'Foo', "FOO\nTESTING" ), - ) ); - } - - public function testUpdate_iwlinks() { - list( $t, $po ) = $this->makeTitleAndParserOutput( "Testing", 111 ); - - $target = Title::makeTitleSafe( NS_MAIN, "Foo", '', 'linksupdatetest' ); - $po->addInterwikiLink( $target ); - - $this->assertLinksUpdate( $t, $po, 'iwlinks', 'iwl_prefix, iwl_title', 'iwl_from = 111', array( - array( 'linksupdatetest', 'Foo' ), - ) ); - } - - public function testUpdate_templatelinks() { - list( $t, $po ) = $this->makeTitleAndParserOutput( "Testing", 111 ); - - $po->addTemplate( Title::newFromText( "Template:Foo" ), 23, 42 ); - - $this->assertLinksUpdate( $t, $po, 'templatelinks', 'tl_namespace, tl_title', 'tl_from = 111', array( - array( NS_TEMPLATE, 'Foo' ), - ) ); - } - - public function testUpdate_imagelinks() { - list( $t, $po ) = $this->makeTitleAndParserOutput( "Testing", 111 ); - - $po->addImage( "Foo.png" ); - - - $this->assertLinksUpdate( $t, $po, 'imagelinks', 'il_to', 'il_from = 111', array( - array( 'Foo.png' ), - ) ); - } - - public function testUpdate_langlinks() { - list( $t, $po ) = $this->makeTitleAndParserOutput( "Testing", 111 ); - - $po->addLanguageLink( Title::newFromText( "en:Foo" ) ); - - - $this->assertLinksUpdate( $t, $po, 'langlinks', 'll_lang, ll_title', 'll_from = 111', array( - array( 'En', 'Foo' ), - ) ); - } - - public function testUpdate_page_props() { - list( $t, $po ) = $this->makeTitleAndParserOutput( "Testing", 111 ); - - $po->setProperty( "foo", "bar" ); - - $this->assertLinksUpdate( $t, $po, 'page_props', 'pp_propname, pp_value', 'pp_page = 111', array( - array( 'foo', 'bar' ), - ) ); - } - - #@todo: test recursive, too! - - protected function assertLinksUpdate( Title $title, ParserOutput $parserOutput, $table, $fields, $condition, Array $expectedRows ) { - $update = new LinksUpdate( $title, $parserOutput ); - - $update->doUpdate(); - - $this->assertSelect( $table, $fields, $condition, $expectedRows ); - } -} - diff --git a/tests/phpunit/includes/LocalFileTest.php b/tests/phpunit/includes/LocalFileTest.php deleted file mode 100644 index 5b26b89c..00000000 --- a/tests/phpunit/includes/LocalFileTest.php +++ /dev/null @@ -1,108 +0,0 @@ - 'test', - 'directory' => '/testdir', - 'url' => '/testurl', - 'hashLevels' => 2, - 'transformVia404' => false, - 'backend' => new FSFileBackend( array( - 'name' => 'local-backend', - 'lockManager' => 'fsLockManager', - 'containerPaths' => array( - 'cont1' => "/testdir/local-backend/tempimages/cont1", - 'cont2' => "/testdir/local-backend/tempimages/cont2" - ) - ) ) - ); - $this->repo_hl0 = new LocalRepo( array( 'hashLevels' => 0 ) + $info ); - $this->repo_hl2 = new LocalRepo( array( 'hashLevels' => 2 ) + $info ); - $this->repo_lc = new LocalRepo( array( 'initialCapital' => false ) + $info ); - $this->file_hl0 = $this->repo_hl0->newFile( 'test!' ); - $this->file_hl2 = $this->repo_hl2->newFile( 'test!' ); - $this->file_lc = $this->repo_lc->newFile( 'test!' ); - } - - function testGetHashPath() { - $this->assertEquals( '', $this->file_hl0->getHashPath() ); - $this->assertEquals( 'a/a2/', $this->file_hl2->getHashPath() ); - $this->assertEquals( 'c/c4/', $this->file_lc->getHashPath() ); - } - - function testGetRel() { - $this->assertEquals( 'Test!', $this->file_hl0->getRel() ); - $this->assertEquals( 'a/a2/Test!', $this->file_hl2->getRel() ); - $this->assertEquals( 'c/c4/test!', $this->file_lc->getRel() ); - } - - function testGetUrlRel() { - $this->assertEquals( 'Test%21', $this->file_hl0->getUrlRel() ); - $this->assertEquals( 'a/a2/Test%21', $this->file_hl2->getUrlRel() ); - $this->assertEquals( 'c/c4/test%21', $this->file_lc->getUrlRel() ); - } - - function testGetArchivePath() { - $this->assertEquals( 'mwstore://local-backend/test-public/archive', $this->file_hl0->getArchivePath() ); - $this->assertEquals( 'mwstore://local-backend/test-public/archive/a/a2', $this->file_hl2->getArchivePath() ); - $this->assertEquals( 'mwstore://local-backend/test-public/archive/!', $this->file_hl0->getArchivePath( '!' ) ); - $this->assertEquals( 'mwstore://local-backend/test-public/archive/a/a2/!', $this->file_hl2->getArchivePath( '!' ) ); - } - - function testGetThumbPath() { - $this->assertEquals( 'mwstore://local-backend/test-thumb/Test!', $this->file_hl0->getThumbPath() ); - $this->assertEquals( 'mwstore://local-backend/test-thumb/a/a2/Test!', $this->file_hl2->getThumbPath() ); - $this->assertEquals( 'mwstore://local-backend/test-thumb/Test!/x', $this->file_hl0->getThumbPath( 'x' ) ); - $this->assertEquals( 'mwstore://local-backend/test-thumb/a/a2/Test!/x', $this->file_hl2->getThumbPath( 'x' ) ); - } - - function testGetArchiveUrl() { - $this->assertEquals( '/testurl/archive', $this->file_hl0->getArchiveUrl() ); - $this->assertEquals( '/testurl/archive/a/a2', $this->file_hl2->getArchiveUrl() ); - $this->assertEquals( '/testurl/archive/%21', $this->file_hl0->getArchiveUrl( '!' ) ); - $this->assertEquals( '/testurl/archive/a/a2/%21', $this->file_hl2->getArchiveUrl( '!' ) ); - } - - function testGetThumbUrl() { - $this->assertEquals( '/testurl/thumb/Test%21', $this->file_hl0->getThumbUrl() ); - $this->assertEquals( '/testurl/thumb/a/a2/Test%21', $this->file_hl2->getThumbUrl() ); - $this->assertEquals( '/testurl/thumb/Test%21/x', $this->file_hl0->getThumbUrl( 'x' ) ); - $this->assertEquals( '/testurl/thumb/a/a2/Test%21/x', $this->file_hl2->getThumbUrl( 'x' ) ); - } - - function testGetArchiveVirtualUrl() { - $this->assertEquals( 'mwrepo://test/public/archive', $this->file_hl0->getArchiveVirtualUrl() ); - $this->assertEquals( 'mwrepo://test/public/archive/a/a2', $this->file_hl2->getArchiveVirtualUrl() ); - $this->assertEquals( 'mwrepo://test/public/archive/%21', $this->file_hl0->getArchiveVirtualUrl( '!' ) ); - $this->assertEquals( 'mwrepo://test/public/archive/a/a2/%21', $this->file_hl2->getArchiveVirtualUrl( '!' ) ); - } - - function testGetThumbVirtualUrl() { - $this->assertEquals( 'mwrepo://test/thumb/Test%21', $this->file_hl0->getThumbVirtualUrl() ); - $this->assertEquals( 'mwrepo://test/thumb/a/a2/Test%21', $this->file_hl2->getThumbVirtualUrl() ); - $this->assertEquals( 'mwrepo://test/thumb/Test%21/%21', $this->file_hl0->getThumbVirtualUrl( '!' ) ); - $this->assertEquals( 'mwrepo://test/thumb/a/a2/Test%21/%21', $this->file_hl2->getThumbVirtualUrl( '!' ) ); - } - - function testGetUrl() { - $this->assertEquals( '/testurl/Test%21', $this->file_hl0->getUrl() ); - $this->assertEquals( '/testurl/a/a2/Test%21', $this->file_hl2->getUrl() ); - } - - function testWfLocalFile() { - $file = wfLocalFile( "File:Some_file_that_probably_doesn't exist.png" ); - $this->assertThat( $file, $this->isInstanceOf( 'LocalFile' ), 'wfLocalFile() returns LocalFile for valid Titles' ); - } -} - - diff --git a/tests/phpunit/includes/LocalisationCacheTest.php b/tests/phpunit/includes/LocalisationCacheTest.php deleted file mode 100644 index 356db87c..00000000 --- a/tests/phpunit/includes/LocalisationCacheTest.php +++ /dev/null @@ -1,31 +0,0 @@ -assertEquals( - $cache->getItem( 'ru', 'pluralRules' ), - $cache->getItem( 'os', 'pluralRules' ), - 'os plural rules (undefined) fallback to ru (defined)' - ); - - $this->assertEquals( - $cache->getItem( 'ru', 'compiledPluralRules' ), - $cache->getItem( 'os', 'compiledPluralRules' ), - 'os compiled plural rules (undefined) fallback to ru (defined)' - ); - - $this->assertNotEquals( - $cache->getItem( 'ksh', 'pluralRules' ), - $cache->getItem( 'de', 'pluralRules' ), - 'ksh plural rules (defined) dont fallback to de (defined)' - ); - - $this->assertNotEquals( - $cache->getItem( 'ksh', 'compiledPluralRules' ), - $cache->getItem( 'de', 'compiledPluralRules' ), - 'ksh compiled plural rules (defined) dont fallback to de (defined)' - ); - } -} diff --git a/tests/phpunit/includes/MWFunctionTest.php b/tests/phpunit/includes/MWFunctionTest.php deleted file mode 100644 index ed5e7602..00000000 --- a/tests/phpunit/includes/MWFunctionTest.php +++ /dev/null @@ -1,86 +0,0 @@ -assertEquals( - call_user_func( array( 'MWFunctionTest', 'someMethod' ) ), - MWFunction::call( 'MWFunctionTest::someMethod' ) - ); - $this->assertEquals( - call_user_func( array( 'MWFunctionTest', 'someMethod' ), 'foo', 'bar', 'baz' ), - MWFunction::call( 'MWFunctionTest::someMethod', 'foo', 'bar', 'baz' ) - ); - - - - $this->assertEquals( - call_user_func_array( array( 'MWFunctionTest', 'someMethod' ), array() ), - MWFunction::callArray( 'MWFunctionTest::someMethod', array() ) - ); - $this->assertEquals( - call_user_func_array( array( 'MWFunctionTest', 'someMethod' ), array( 'foo', 'bar', 'baz' ) ), - MWFunction::callArray( 'MWFunctionTest::someMethod', array( 'foo', 'bar', 'baz' ) ) - ); - - } - - function testNewObjFunction() { - - $arg1 = 'Foo'; - $arg2 = 'Bar'; - $arg3 = array( 'Baz' ); - $arg4 = new ExampleObject; - - $args = array( $arg1, $arg2, $arg3, $arg4 ); - - $newObject = new MWBlankClass( $arg1, $arg2, $arg3, $arg4 ); - - $this->assertEquals( - MWFunction::newObj( 'MWBlankClass', $args )->args, - $newObject->args - ); - - $this->assertEquals( - MWFunction::newObj( 'MWBlankClass', $args, true )->args, - $newObject->args, - 'Works even with PHP version < 5.1.3' - ); - - } - - /** - * @expectedException MWException - */ - function testCallingParentFails() { - - MWFunction::call( 'parent::foo' ); - } - - /** - * @expectedException MWException - */ - function testCallingSelfFails() { - - MWFunction::call( 'self::foo' ); - } - - public static function someMethod() { - return func_get_args(); - } - -} - -class MWBlankClass { - - public $args = array(); - - function __construct( $arg1, $arg2, $arg3, $arg4 ) { - $this->args = array( $arg1, $arg2, $arg3, $arg4 ); - } - -} - -class ExampleObject { -} diff --git a/tests/phpunit/includes/MWNamespaceTest.php b/tests/phpunit/includes/MWNamespaceTest.php deleted file mode 100644 index 3b05d675..00000000 --- a/tests/phpunit/includes/MWNamespaceTest.php +++ /dev/null @@ -1,628 +0,0 @@ -assertFalse( MWNamespace::isMovable( NS_CATEGORY ) ); - # @todo FIXME: Write more tests!! - } - - /** - * Please make sure to change testIsTalk() if you change the assertions below - */ - public function testIsSubject() { - // Special namespaces - $this->assertIsSubject( NS_MEDIA ); - $this->assertIsSubject( NS_SPECIAL ); - - // Subject pages - $this->assertIsSubject( NS_MAIN ); - $this->assertIsSubject( NS_USER ); - $this->assertIsSubject( 100 ); # user defined - - // Talk pages - $this->assertIsNotSubject( NS_TALK ); - $this->assertIsNotSubject( NS_USER_TALK ); - $this->assertIsNotSubject( 101 ); # user defined - } - - /** - * Reverse of testIsSubject(). - * Please update testIsSubject() if you change assertions below - */ - public function testIsTalk() { - // Special namespaces - $this->assertIsNotTalk( NS_MEDIA ); - $this->assertIsNotTalk( NS_SPECIAL ); - - // Subject pages - $this->assertIsNotTalk( NS_MAIN ); - $this->assertIsNotTalk( NS_USER ); - $this->assertIsNotTalk( 100 ); # user defined - - // Talk pages - $this->assertIsTalk( NS_TALK ); - $this->assertIsTalk( NS_USER_TALK ); - $this->assertIsTalk( 101 ); # user defined - } - - /** - */ - public function testGetSubject() { - // Special namespaces are their own subjects - $this->assertEquals( NS_MEDIA, MWNamespace::getSubject( NS_MEDIA ) ); - $this->assertEquals( NS_SPECIAL, MWNamespace::getSubject( NS_SPECIAL ) ); - - $this->assertEquals( NS_MAIN, MWNamespace::getSubject( NS_TALK ) ); - $this->assertEquals( NS_USER, MWNamespace::getSubject( NS_USER_TALK ) ); - } - - /** - * Regular getTalk() calls - * Namespaces without a talk page (NS_MEDIA, NS_SPECIAL) are tested in - * the function testGetTalkExceptions() - */ - public function testGetTalk() { - $this->assertEquals( NS_TALK, MWNamespace::getTalk( NS_MAIN ) ); - $this->assertEquals( NS_TALK, MWNamespace::getTalk( NS_TALK ) ); - $this->assertEquals( NS_USER_TALK, MWNamespace::getTalk( NS_USER ) ); - $this->assertEquals( NS_USER_TALK, MWNamespace::getTalk( NS_USER_TALK ) ); - } - - /** - * Exceptions with getTalk() - * NS_MEDIA does not have talk pages. MediaWiki raise an exception for them. - * @expectedException MWException - */ - public function testGetTalkExceptionsForNsMedia() { - $this->assertNull( MWNamespace::getTalk( NS_MEDIA ) ); - } - - /** - * Exceptions with getTalk() - * NS_SPECIAL does not have talk pages. MediaWiki raise an exception for them. - * @expectedException MWException - */ - public function testGetTalkExceptionsForNsSpecial() { - $this->assertNull( MWNamespace::getTalk( NS_SPECIAL ) ); - } - - /** - * Regular getAssociated() calls - * Namespaces without an associated page (NS_MEDIA, NS_SPECIAL) are tested in - * the function testGetAssociatedExceptions() - */ - public function testGetAssociated() { - $this->assertEquals( NS_TALK, MWNamespace::getAssociated( NS_MAIN ) ); - $this->assertEquals( NS_MAIN, MWNamespace::getAssociated( NS_TALK ) ); - - } - - ### Exceptions with getAssociated() - ### NS_MEDIA and NS_SPECIAL do not have talk pages. MediaWiki raises - ### an exception for them. - /** - * @expectedException MWException - */ - public function testGetAssociatedExceptionsForNsMedia() { - $this->assertNull( MWNamespace::getAssociated( NS_MEDIA ) ); - } - - /** - * @expectedException MWException - */ - public function testGetAssociatedExceptionsForNsSpecial() { - $this->assertNull( MWNamespace::getAssociated( NS_SPECIAL ) ); - } - - /** - * @todo Implement testExists(). - */ -/* - public function testExists() { - // Remove the following lines when you implement this test. - $this->markTestIncomplete( - 'This test has not been implemented yet. Rely on $wgCanonicalNamespaces.' - ); - } -*/ - - /** - * Test MWNamespace::equals - * Note if we add a namespace registration system with keys like 'MAIN' - * we should add tests here for equivilance on things like 'MAIN' == 0 - * and 'MAIN' == NS_MAIN. - */ - public function testEquals() { - $this->assertTrue( MWNamespace::equals( NS_MAIN, NS_MAIN ) ); - $this->assertTrue( MWNamespace::equals( NS_MAIN, 0 ) ); // In case we make NS_MAIN 'MAIN' - $this->assertTrue( MWNamespace::equals( NS_USER, NS_USER ) ); - $this->assertTrue( MWNamespace::equals( NS_USER, 2 ) ); - $this->assertTrue( MWNamespace::equals( NS_USER_TALK, NS_USER_TALK ) ); - $this->assertTrue( MWNamespace::equals( NS_SPECIAL, NS_SPECIAL ) ); - $this->assertFalse( MWNamespace::equals( NS_MAIN, NS_TALK ) ); - $this->assertFalse( MWNamespace::equals( NS_USER, NS_USER_TALK ) ); - $this->assertFalse( MWNamespace::equals( NS_PROJECT, NS_TEMPLATE ) ); - } - - /** - * Test MWNamespace::subjectEquals - */ - public function testSubjectEquals() { - $this->assertSameSubject( NS_MAIN, NS_MAIN ); - $this->assertSameSubject( NS_MAIN, 0 ); // In case we make NS_MAIN 'MAIN' - $this->assertSameSubject( NS_USER, NS_USER ); - $this->assertSameSubject( NS_USER, 2 ); - $this->assertSameSubject( NS_USER_TALK, NS_USER_TALK ); - $this->assertSameSubject( NS_SPECIAL, NS_SPECIAL ); - $this->assertSameSubject( NS_MAIN, NS_TALK ); - $this->assertSameSubject( NS_USER, NS_USER_TALK ); - - $this->assertDifferentSubject( NS_PROJECT, NS_TEMPLATE ); - $this->assertDifferentSubject( NS_SPECIAL, NS_MAIN ); - } - - public function testSpecialAndMediaAreDifferentSubjects() { - $this->assertDifferentSubject( - NS_MEDIA, NS_SPECIAL, - "NS_MEDIA and NS_SPECIAL are different subject namespaces" - ); - $this->assertDifferentSubject( - NS_SPECIAL, NS_MEDIA, - "NS_SPECIAL and NS_MEDIA are different subject namespaces" - ); - - } - - /** - * @todo Implement testGetCanonicalNamespaces(). - */ -/* - public function testGetCanonicalNamespaces() { - // Remove the following lines when you implement this test. - $this->markTestIncomplete( - 'This test has not been implemented yet. Rely on $wgCanonicalNamespaces.' - ); - } -*/ - /** - * @todo Implement testGetCanonicalName(). - */ -/* - public function testGetCanonicalName() { - // Remove the following lines when you implement this test. - $this->markTestIncomplete( - 'This test has not been implemented yet. Rely on $wgCanonicalNamespaces.' - ); - } -*/ - /** - * @todo Implement testGetCanonicalIndex(). - */ -/* - public function testGetCanonicalIndex() { - // Remove the following lines when you implement this test. - $this->markTestIncomplete( - 'This test has not been implemented yet. Rely on $wgCanonicalNamespaces.' - ); - } -*/ - /** - * @todo Implement testGetValidNamespaces(). - */ -/* - public function testGetValidNamespaces() { - // Remove the following lines when you implement this test. - $this->markTestIncomplete( - 'This test has not been implemented yet. Rely on $wgCanonicalNamespaces.' - ); - } -*/ - /** - */ - public function testCanTalk() { - $this->assertCanNotTalk( NS_MEDIA ); - $this->assertCanNotTalk( NS_SPECIAL ); - - $this->assertCanTalk( NS_MAIN ); - $this->assertCanTalk( NS_TALK ); - $this->assertCanTalk( NS_USER ); - $this->assertCanTalk( NS_USER_TALK ); - - // User defined namespaces - $this->assertCanTalk( 100 ); - $this->assertCanTalk( 101 ); - } - - /** - */ - public function testIsContent() { - // NS_MAIN is a content namespace per DefaultSettings.php - // and per function definition. - $this->assertIsContent( NS_MAIN ); - - global $wgContentNamespaces; - - $saved = $wgContentNamespaces; - - $wgContentNamespaces[] = NS_MAIN; - $this->assertIsContent( NS_MAIN ); - - // Other namespaces which are not expected to be content - if ( isset( $wgContentNamespaces[NS_MEDIA] ) ) { - unset( $wgContentNamespaces[NS_MEDIA] ); - } - $this->assertIsNotContent( NS_MEDIA ); - - if ( isset( $wgContentNamespaces[NS_SPECIAL] ) ) { - unset( $wgContentNamespaces[NS_SPECIAL] ); - } - $this->assertIsNotContent( NS_SPECIAL ); - - if ( isset( $wgContentNamespaces[NS_TALK] ) ) { - unset( $wgContentNamespaces[NS_TALK] ); - } - $this->assertIsNotContent( NS_TALK ); - - if ( isset( $wgContentNamespaces[NS_USER] ) ) { - unset( $wgContentNamespaces[NS_USER] ); - } - $this->assertIsNotContent( NS_USER ); - - if ( isset( $wgContentNamespaces[NS_CATEGORY] ) ) { - unset( $wgContentNamespaces[NS_CATEGORY] ); - } - $this->assertIsNotContent( NS_CATEGORY ); - - if ( isset( $wgContentNamespaces[100] ) ) { - unset( $wgContentNamespaces[100] ); - } - $this->assertIsNotContent( 100 ); - - $wgContentNamespaces = $saved; - } - - /** - * Similar to testIsContent() but alters the $wgContentNamespaces - * global variable. - */ - public function testIsContentWithAdditionsInWgContentNamespaces() { - // NS_MAIN is a content namespace per DefaultSettings.php - // and per function definition. - $this->assertIsContent( NS_MAIN ); - - // Tests that user defined namespace #252 is not content: - $this->assertIsNotContent( 252 ); - - # @todo FIXME: Is global saving really required for PHPUnit? - // Bless namespace # 252 as a content namespace - global $wgContentNamespaces; - $savedGlobal = $wgContentNamespaces; - $wgContentNamespaces[] = 252; - $this->assertIsContent( 252 ); - - // Makes sure NS_MAIN was not impacted - $this->assertIsContent( NS_MAIN ); - - // Restore global - $wgContentNamespaces = $savedGlobal; - - // Verify namespaces after global restauration - $this->assertIsContent( NS_MAIN ); - $this->assertIsNotContent( 252 ); - } - - public function testIsWatchable() { - // Specials namespaces are not watchable - $this->assertIsNotWatchable( NS_MEDIA ); - $this->assertIsNotWatchable( NS_SPECIAL ); - - // Core defined namespaces are watchables - $this->assertIsWatchable( NS_MAIN ); - $this->assertIsWatchable( NS_TALK ); - - // Additional, user defined namespaces are watchables - $this->assertIsWatchable( 100 ); - $this->assertIsWatchable( 101 ); - } - - public function testHasSubpages() { - // Special namespaces: - $this->assertHasNotSubpages( NS_MEDIA ); - $this->assertHasNotSubpages( NS_SPECIAL ); - - // namespaces without subpages - # save up global - global $wgNamespacesWithSubpages; - $saved = null; - if( array_key_exists( NS_MAIN, $wgNamespacesWithSubpages ) ) { - $saved = $wgNamespacesWithSubpages[NS_MAIN]; - unset( $wgNamespacesWithSubpages[NS_MAIN] ); - } - - $this->assertHasNotSubpages( NS_MAIN ); - - $wgNamespacesWithSubpages[NS_MAIN] = true; - $this->assertHasSubpages( NS_MAIN ); - $wgNamespacesWithSubpages[NS_MAIN] = false; - $this->assertHasNotSubpages( NS_MAIN ); - - # restore global - if( $saved !== null ) { - $wgNamespacesWithSubpages[NS_MAIN] = $saved; - } - - // Some namespaces with subpages - $this->assertHasSubpages( NS_TALK ); - $this->assertHasSubpages( NS_USER ); - $this->assertHasSubpages( NS_USER_TALK ); - } - - /** - */ - public function testGetContentNamespaces() { - $this->assertEquals( - array( NS_MAIN ), - MWNamespace::getcontentNamespaces(), - '$wgContentNamespaces is an array with only NS_MAIN by default' - ); - - global $wgContentNamespaces; - - $saved = $wgContentNamespaces; - # test !is_array( $wgcontentNamespaces ) - $wgContentNamespaces = ''; - $this->assertEquals( NS_MAIN, MWNamespace::getcontentNamespaces() ); - $wgContentNamespaces = false; - $this->assertEquals( NS_MAIN, MWNamespace::getcontentNamespaces() ); - $wgContentNamespaces = null; - $this->assertEquals( NS_MAIN, MWNamespace::getcontentNamespaces() ); - $wgContentNamespaces = 5; - $this->assertEquals( NS_MAIN, MWNamespace::getcontentNamespaces() ); - - # test $wgContentNamespaces === array() - $wgContentNamespaces = array(); - $this->assertEquals( NS_MAIN, MWNamespace::getcontentNamespaces() ); - - # test !in_array( NS_MAIN, $wgContentNamespaces ) - $wgContentNamespaces = array( NS_USER, NS_CATEGORY ); - $this->assertEquals( - array( NS_MAIN, NS_USER, NS_CATEGORY ), - MWNamespace::getcontentNamespaces(), - 'NS_MAIN is forced in $wgContentNamespaces even if unwanted' - ); - - # test other cases, return $wgcontentNamespaces as is - $wgContentNamespaces = array( NS_MAIN ); - $this->assertEquals( - array( NS_MAIN ), - MWNamespace::getcontentNamespaces() - ); - - $wgContentNamespaces = array( NS_MAIN, NS_USER, NS_CATEGORY ); - $this->assertEquals( - array( NS_MAIN, NS_USER, NS_CATEGORY ), - MWNamespace::getcontentNamespaces() - ); - - $wgContentNamespaces = $saved; - } - - /** - */ - public function testGetSubjectNamespaces() { - $subjectsNS = MWNamespace::getSubjectNamespaces(); - $this->assertContains( NS_MAIN, $subjectsNS, - "Talk namespaces should have NS_MAIN" ); - $this->assertNotContains( NS_TALK, $subjectsNS, - "Talk namespaces should have NS_TALK" ); - - $this->assertNotContains( NS_MEDIA, $subjectsNS, - "Talk namespaces should not have NS_MEDIA" ); - $this->assertNotContains( NS_SPECIAL, $subjectsNS, - "Talk namespaces should not have NS_SPECIAL" ); - } - - /** - */ - public function testGetTalkNamespaces() { - $talkNS = MWNamespace::getTalkNamespaces(); - $this->assertContains( NS_TALK, $talkNS, - "Subject namespaces should have NS_TALK" ); - $this->assertNotContains( NS_MAIN, $talkNS, - "Subject namespaces should not have NS_MAIN" ); - - $this->assertNotContains( NS_MEDIA, $talkNS, - "Subject namespaces should not have NS_MEDIA" ); - $this->assertNotContains( NS_SPECIAL, $talkNS, - "Subject namespaces should not have NS_SPECIAL" ); - } - - /** - * Some namespaces are always capitalized per code definition - * in MWNamespace::$alwaysCapitalizedNamespaces - */ - public function testIsCapitalizedHardcodedAssertions() { - // NS_MEDIA and NS_FILE are treated the same - $this->assertEquals( - MWNamespace::isCapitalized( NS_MEDIA ), - MWNamespace::isCapitalized( NS_FILE ), - 'NS_MEDIA and NS_FILE have same capitalization rendering' - ); - - // Boths are capitalized by default - $this->assertIsCapitalized( NS_MEDIA ); - $this->assertIsCapitalized( NS_FILE ); - - // Always capitalized namespaces - // @see MWNamespace::$alwaysCapitalizedNamespaces - $this->assertIsCapitalized( NS_SPECIAL ); - $this->assertIsCapitalized( NS_USER ); - $this->assertIsCapitalized( NS_MEDIAWIKI ); - } - - /** - * Follows up for testIsCapitalizedHardcodedAssertions() but alter the - * global $wgCapitalLink setting to have extended coverage. - * - * MWNamespace::isCapitalized() rely on two global settings: - * $wgCapitalLinkOverrides = array(); by default - * $wgCapitalLinks = true; by default - * This function test $wgCapitalLinks - * - * Global setting correctness is tested against the NS_PROJECT and - * NS_PROJECT_TALK namespaces since they are not hardcoded nor specials - */ - public function testIsCapitalizedWithWgCapitalLinks() { - global $wgCapitalLinks; - // Save the global to easily reset to MediaWiki default settings - $savedGlobal = $wgCapitalLinks; - - $wgCapitalLinks = true; - $this->assertIsCapitalized( NS_PROJECT ); - $this->assertIsCapitalized( NS_PROJECT_TALK ); - - $wgCapitalLinks = false; - // hardcoded namespaces (see above function) are still capitalized: - $this->assertIsCapitalized( NS_SPECIAL ); - $this->assertIsCapitalized( NS_USER ); - $this->assertIsCapitalized( NS_MEDIAWIKI ); - // setting is correctly applied - $this->assertIsNotCapitalized( NS_PROJECT ); - $this->assertIsNotCapitalized( NS_PROJECT_TALK ); - - // reset global state: - $wgCapitalLinks = $savedGlobal; - } - - /** - * Counter part for MWNamespace::testIsCapitalizedWithWgCapitalLinks() now - * testing the $wgCapitalLinkOverrides global. - * - * @todo split groups of assertions in autonomous testing functions - */ - public function testIsCapitalizedWithWgCapitalLinkOverrides() { - global $wgCapitalLinkOverrides; - // Save the global to easily reset to MediaWiki default settings - $savedGlobal = $wgCapitalLinkOverrides; - - // Test default settings - $this->assertIsCapitalized( NS_PROJECT ); - $this->assertIsCapitalized( NS_PROJECT_TALK ); - // hardcoded namespaces (see above function) are capitalized: - $this->assertIsCapitalized( NS_SPECIAL ); - $this->assertIsCapitalized( NS_USER ); - $this->assertIsCapitalized( NS_MEDIAWIKI ); - - // Hardcoded namespaces remains capitalized - $wgCapitalLinkOverrides[NS_SPECIAL] = false; - $wgCapitalLinkOverrides[NS_USER] = false; - $wgCapitalLinkOverrides[NS_MEDIAWIKI] = false; - $this->assertIsCapitalized( NS_SPECIAL ); - $this->assertIsCapitalized( NS_USER ); - $this->assertIsCapitalized( NS_MEDIAWIKI ); - - $wgCapitalLinkOverrides = $savedGlobal; - $wgCapitalLinkOverrides[NS_PROJECT] = false; - $this->assertIsNotCapitalized( NS_PROJECT ); - $wgCapitalLinkOverrides[NS_PROJECT] = true ; - $this->assertIsCapitalized( NS_PROJECT ); - unset( $wgCapitalLinkOverrides[NS_PROJECT] ); - $this->assertIsCapitalized( NS_PROJECT ); - - // reset global state: - $wgCapitalLinkOverrides = $savedGlobal; - } - - public function testHasGenderDistinction() { - // Namespaces with gender distinctions - $this->assertTrue( MWNamespace::hasGenderDistinction( NS_USER ) ); - $this->assertTrue( MWNamespace::hasGenderDistinction( NS_USER_TALK ) ); - - // Other ones, "genderless" - $this->assertFalse( MWNamespace::hasGenderDistinction( NS_MEDIA ) ); - $this->assertFalse( MWNamespace::hasGenderDistinction( NS_SPECIAL ) ); - $this->assertFalse( MWNamespace::hasGenderDistinction( NS_MAIN ) ); - $this->assertFalse( MWNamespace::hasGenderDistinction( NS_TALK ) ); - - } - - public function testIsNonincludable() { - global $wgNonincludableNamespaces; - $wgNonincludableNamespaces = array( NS_USER ); - - $this->assertTrue( MWNamespace::isNonincludable( NS_USER ) ); - - $this->assertFalse( MWNamespace::isNonincludable( NS_TEMPLATE ) ); - } - - ####### HELPERS ########################################################### - function __call( $method, $args ) { - // Call the real method if it exists - if( method_exists($this, $method ) ) { - return $this->$method( $args ); - } - - if( preg_match( '/^assert(Has|Is|Can)(Not|)(Subject|Talk|Watchable|Content|Subpages|Capitalized)$/', $method, $m ) ) { - # Interprets arguments: - $ns = $args[0]; - $msg = isset($args[1]) ? $args[1] : " dummy message"; - - # Forge the namespace constant name: - if( $ns === 0 ) { - $ns_name = "NS_MAIN"; - } else { - $ns_name = "NS_" . strtoupper( MWNamespace::getCanonicalName( $ns ) ); - } - # ... and the MWNamespace method name - $nsMethod = strtolower( $m[1] ) . $m[3]; - - $expect = ($m[2] === ''); - $expect_name = $expect ? 'TRUE' : 'FALSE'; - - return $this->assertEquals( $expect, - MWNamespace::$nsMethod( $ns, $msg ), - "MWNamespace::$nsMethod( $ns_name ) should returns $expect_name" - ); - } - - throw new Exception( __METHOD__ . " could not find a method named $method\n" ); - } - - function assertSameSubject( $ns1, $ns2, $msg = '' ) { - $this->assertTrue( MWNamespace::subjectEquals( $ns1, $ns2, $msg ) ); - } - function assertDifferentSubject( $ns1, $ns2, $msg = '' ) { - $this->assertFalse( MWNamespace::subjectEquals( $ns1, $ns2, $msg ) ); - } -} - diff --git a/tests/phpunit/includes/MessageTest.php b/tests/phpunit/includes/MessageTest.php deleted file mode 100644 index 20181fd4..00000000 --- a/tests/phpunit/includes/MessageTest.php +++ /dev/null @@ -1,64 +0,0 @@ -assertTrue( wfMessage( 'mainpage' )->exists() ); - $this->assertTrue( wfMessage( 'mainpage' )->params( array() )->exists() ); - $this->assertTrue( wfMessage( 'mainpage' )->rawParams( 'foo', 123 )->exists() ); - $this->assertFalse( wfMessage( 'i-dont-exist-evar' )->exists() ); - $this->assertFalse( wfMessage( 'i-dont-exist-evar' )->params( array() )->exists() ); - $this->assertFalse( wfMessage( 'i-dont-exist-evar' )->rawParams( 'foo', 123 )->exists() ); - } - - function testKey() { - $this->assertInstanceOf( 'Message', wfMessage( 'mainpage' ) ); - $this->assertInstanceOf( 'Message', wfMessage( 'i-dont-exist-evar' ) ); - $this->assertEquals( 'Main Page', wfMessage( 'mainpage' )->text() ); - $this->assertEquals( '<i-dont-exist-evar>', wfMessage( 'i-dont-exist-evar' )->text() ); - $this->assertEquals( '', wfMessage( 'i-dont-exist-evar' )->plain() ); - $this->assertEquals( '<i-dont-exist-evar>', wfMessage( 'i-dont-exist-evar' )->escaped() ); - } - - function testInLanguage() { - $this->assertEquals( 'Main Page', wfMessage( 'mainpage' )->inLanguage( 'en' )->text() ); - $this->assertEquals( 'Заглавная страница', wfMessage( 'mainpage' )->inLanguage( 'ru' )->text() ); - $this->assertEquals( 'Main Page', wfMessage( 'mainpage' )->inLanguage( Language::factory( 'en' ) )->text() ); - $this->assertEquals( 'Заглавная страница', wfMessage( 'mainpage' )->inLanguage( Language::factory( 'ru' ) )->text() ); - } - - function testMessageParams() { - $this->assertEquals( 'Return to $1.', wfMessage( 'returnto' )->text() ); - $this->assertEquals( 'Return to $1.', wfMessage( 'returnto', array() )->text() ); - $this->assertEquals( 'You have foo (bar).', wfMessage( 'youhavenewmessages', 'foo', 'bar' )->text() ); - $this->assertEquals( 'You have foo (bar).', wfMessage( 'youhavenewmessages', array( 'foo', 'bar' ) )->text() ); - } - - function testMessageParamSubstitution() { - $this->assertEquals( '(Заглавная страница)', wfMessage( 'parentheses', 'Заглавная страница' )->plain() ); - $this->assertEquals( '(Заглавная страница $1)', wfMessage( 'parentheses', 'Заглавная страница $1' )->plain() ); - $this->assertEquals( '(Заглавная страница)', wfMessage( 'parentheses' )->rawParams( 'Заглавная страница' )->plain() ); - $this->assertEquals( '(Заглавная страница $1)', wfMessage( 'parentheses' )->rawParams( 'Заглавная страница $1' )->plain() ); - } - - function testInContentLanguage() { - global $wgLang, $wgForceUIMsgAsContentMsg; - $oldLang = $wgLang; - $wgLang = Language::factory( 'fr' ); - - $this->assertEquals( 'Main Page', wfMessage( 'mainpage' )->inContentLanguage()->plain(), 'ForceUIMsg disabled' ); - $wgForceUIMsgAsContentMsg['testInContentLanguage'] = 'mainpage'; - $this->assertEquals( 'Accueil', wfMessage( 'mainpage' )->inContentLanguage()->plain(), 'ForceUIMsg enabled' ); - - /* Restore globals */ - $wgLang = $oldLang; - unset( $wgForceUIMsgAsContentMsg['testInContentLanguage'] ); - } - - /** - * @expectedException MWException - */ - function testInLanguageThrows() { - wfMessage( 'foo' )->inLanguage( 123 ); - } -} diff --git a/tests/phpunit/includes/ParserOptionsTest.php b/tests/phpunit/includes/ParserOptionsTest.php deleted file mode 100644 index 59c955fe..00000000 --- a/tests/phpunit/includes/ParserOptionsTest.php +++ /dev/null @@ -1,35 +0,0 @@ -popts = ParserOptions::newFromUserAndLang( $wgUser, $wgContLang ); - $this->pcache = ParserCache::singleton(); - } - - function tearDown() { - parent::tearDown(); - } - - /** - * ParserOptions::optionsHash was not giving consistent results when $wgUseDynamicDates was set - * @group Database - */ - function testGetParserCacheKeyWithDynamicDates() { - global $wgUseDynamicDates; - $wgUseDynamicDates = true; - - $title = Title::newFromText( "Some test article" ); - $page = WikiPage::factory( $title ); - - $pcacheKeyBefore = $this->pcache->getKey( $page, $this->popts ); - $this->assertNotNull( $this->popts->getDateFormat() ); - $pcacheKeyAfter = $this->pcache->getKey( $page, $this->popts ); - $this->assertEquals( $pcacheKeyBefore, $pcacheKeyAfter ); - } -} diff --git a/tests/phpunit/includes/PathRouterTest.php b/tests/phpunit/includes/PathRouterTest.php deleted file mode 100644 index f6274584..00000000 --- a/tests/phpunit/includes/PathRouterTest.php +++ /dev/null @@ -1,254 +0,0 @@ -add("/wiki/$1"); - $this->basicRouter = $router; - } - - /** - * Test basic path parsing - */ - public function testBasic() { - $matches = $this->basicRouter->parse( "/wiki/Foo" ); - $this->assertEquals( $matches, array( 'title' => "Foo" ) ); - } - - /** - * Test loose path auto-$1 - */ - public function testLoose() { - $router = new PathRouter; - $router->add("/"); # Should be the same as "/$1" - $matches = $router->parse( "/Foo" ); - $this->assertEquals( $matches, array( 'title' => "Foo" ) ); - - $router = new PathRouter; - $router->add("/wiki"); # Should be the same as /wiki/$1 - $matches = $router->parse( "/wiki/Foo" ); - $this->assertEquals( $matches, array( 'title' => "Foo" ) ); - - $router = new PathRouter; - $router->add("/wiki/"); # Should be the same as /wiki/$1 - $matches = $router->parse( "/wiki/Foo" ); - $this->assertEquals( $matches, array( 'title' => "Foo" ) ); - } - - /** - * Test to ensure that path is based on specifity, not order - */ - public function testOrder() { - $router = new PathRouter; - $router->add("/$1"); - $router->add("/a/$1"); - $router->add("/b/$1"); - $matches = $router->parse( "/a/Foo" ); - $this->assertEquals( $matches, array( 'title' => "Foo" ) ); - - $router = new PathRouter; - $router->add("/b/$1"); - $router->add("/a/$1"); - $router->add("/$1"); - $matches = $router->parse( "/a/Foo" ); - $this->assertEquals( $matches, array( 'title' => "Foo" ) ); - } - - /** - * Test the handling of key based arrays with a url parameter - */ - public function testKeyParameter() { - $router = new PathRouter; - $router->add( array( 'edit' => "/edit/$1" ), array( 'action' => '$key' ) ); - $matches = $router->parse( "/edit/Foo" ); - $this->assertEquals( $matches, array( 'title' => "Foo", 'action' => 'edit' ) ); - } - - /** - * Test the handling of $2 inside paths - */ - public function testAdditionalParameter() { - // Basic $2 - $router = new PathRouter; - $router->add( '/$2/$1', array( 'test' => '$2' ) ); - $matches = $router->parse( "/asdf/Foo" ); - $this->assertEquals( $matches, array( 'title' => "Foo", 'test' => 'asdf' ) ); - } - - /** - * Test additional restricted value parameter - */ - public function testRestrictedValue() { - $router = new PathRouter; - $router->add( '/$2/$1', - array( 'test' => '$2' ), - array( '$2' => array( 'a', 'b' ) ) - ); - $router->add( '/$2/$1', - array( 'test2' => '$2' ), - array( '$2' => 'c' ) - ); - $router->add( '/$1' ); - - $matches = $router->parse( "/asdf/Foo" ); - $this->assertEquals( $matches, array( 'title' => "asdf/Foo" ) ); - - $matches = $router->parse( "/a/Foo" ); - $this->assertEquals( $matches, array( 'title' => "Foo", 'test' => 'a' ) ); - - $matches = $router->parse( "/c/Foo" ); - $this->assertEquals( $matches, array( 'title' => "Foo", 'test2' => 'c' ) ); - } - - public function callbackForTest( &$matches, $data ) { - $matches['x'] = $data['$1']; - $matches['foo'] = $data['foo']; - } - - public function testCallback() { - $router = new PathRouter; - $router->add( "/$1", - array( 'a' => 'b', 'data:foo' => 'bar' ), - array( 'callback' => array( $this, 'callbackForTest' ) ) - ); - $matches = $router->parse( '/Foo' ); - $this->assertEquals( $matches, array( - 'title' => "Foo", - 'x' => 'Foo', - 'a' => 'b', - 'foo' => 'bar' - ) ); - } - - /** - * Test to ensure that matches are not made if a parameter expects nonexistent input - */ - public function testFail() { - $router = new PathRouter; - $router->add( "/wiki/$1", array( 'title' => "$1$2" ) ); - $matches = $router->parse( "/wiki/A" ); - $this->assertEquals( array(), $matches ); - } - - /** - * Test to ensure weight of paths is handled correctly - */ - public function testWeight() { - $router = new PathRouter; - $router->addStrict( "/Bar", array( 'ping' => 'pong' ) ); - $router->add( "/asdf-$1", array( 'title' => 'qwerty-$1' ) ); - $router->add( "/$1" ); - $router->add( "/qwerty-$1", array( 'title' => 'asdf-$1' ) ); - $router->addStrict( "/Baz", array( 'marco' => 'polo' ) ); - $router->add( "/a/$1" ); - $router->add( "/asdf/$1" ); - $router->add( "/$2/$1", array( 'unrestricted' => '$2' ) ); - $router->add( array( 'qwerty' => "/qwerty/$1" ), array( 'qwerty' => '$key' ) ); - $router->add( "/$2/$1", array( 'restricted-to-y' => '$2' ), array( '$2' => 'y' ) ); - - foreach( array( - "/Foo" => array( 'title' => "Foo" ), - "/Bar" => array( 'ping' => 'pong' ), - "/Baz" => array( 'marco' => 'polo' ), - "/asdf-foo" => array( 'title' => "qwerty-foo" ), - "/qwerty-bar" => array( 'title' => "asdf-bar" ), - "/a/Foo" => array( 'title' => "Foo" ), - "/asdf/Foo" => array( 'title' => "Foo" ), - "/qwerty/Foo" => array( 'title' => "Foo", 'qwerty' => 'qwerty' ), - "/baz/Foo" => array( 'title' => "Foo", 'unrestricted' => 'baz' ), - "/y/Foo" => array( 'title' => "Foo", 'restricted-to-y' => 'y' ), - ) as $path => $result ) { - $this->assertEquals( $router->parse( $path ), $result ); - } - } - - /** - * Make sure the router handles titles like Special:Recentchanges correctly - */ - public function testSpecial() { - $matches = $this->basicRouter->parse( "/wiki/Special:Recentchanges" ); - $this->assertEquals( $matches, array( 'title' => "Special:Recentchanges" ) ); - } - - /** - * Make sure the router decodes urlencoding properly - */ - public function testUrlencoding() { - $matches = $this->basicRouter->parse( "/wiki/Title_With%20Space" ); - $this->assertEquals( $matches, array( 'title' => "Title_With Space" ) ); - } - - public function dataRegexpChars() { - return array( - array( "$" ), - array( "$1" ), - array( "\\" ), - array( "\\$1" ), - ); - } - - /** - * Make sure the router doesn't break on special characters like $ used in regexp replacements - * @dataProvider dataRegexpChars - */ - public function testRegexpChars( $char ) { - $matches = $this->basicRouter->parse( "/wiki/$char" ); - $this->assertEquals( $matches, array( 'title' => "$char" ) ); - } - - /** - * Make sure the router handles characters like +&() properly - */ - public function testCharacters() { - $matches = $this->basicRouter->parse( "/wiki/Plus+And&Dollar\\Stuff();[]{}*" ); - $this->assertEquals( $matches, array( 'title' => "Plus+And&Dollar\\Stuff();[]{}*" ) ); - } - - /** - * Make sure the router handles unicode characters correctly - * @depends testSpecial - * @depends testUrlencoding - * @depends testCharacters - */ - public function testUnicode() { - $matches = $this->basicRouter->parse( "/wiki/Spécial:Modifications_récentes" ); - $this->assertEquals( $matches, array( 'title' => "Spécial:Modifications_récentes" ) ); - - $matches = $this->basicRouter->parse( "/wiki/Sp%C3%A9cial:Modifications_r%C3%A9centes" ); - $this->assertEquals( $matches, array( 'title' => "Spécial:Modifications_récentes" ) ); - } - - /** - * Ensure the router doesn't choke on long paths. - */ - public function testLength() { - $matches = $this->basicRouter->parse( "/wiki/Lorem_ipsum_dolor_sit_amet,_consectetur_adipisicing_elit,_sed_do_eiusmod_tempor_incididunt_ut_labore_et_dolore_magna_aliqua._Ut_enim_ad_minim_veniam,_quis_nostrud_exercitation_ullamco_laboris_nisi_ut_aliquip_ex_ea_commodo_consequat._Duis_aute_irure_dolor_in_reprehenderit_in_voluptate_velit_esse_cillum_dolore_eu_fugiat_nulla_pariatur._Excepteur_sint_occaecat_cupidatat_non_proident,_sunt_in_culpa_qui_officia_deserunt_mollit_anim_id_est_laborum." ); - $this->assertEquals( $matches, array( 'title' => "Lorem_ipsum_dolor_sit_amet,_consectetur_adipisicing_elit,_sed_do_eiusmod_tempor_incididunt_ut_labore_et_dolore_magna_aliqua._Ut_enim_ad_minim_veniam,_quis_nostrud_exercitation_ullamco_laboris_nisi_ut_aliquip_ex_ea_commodo_consequat._Duis_aute_irure_dolor_in_reprehenderit_in_voluptate_velit_esse_cillum_dolore_eu_fugiat_nulla_pariatur._Excepteur_sint_occaecat_cupidatat_non_proident,_sunt_in_culpa_qui_officia_deserunt_mollit_anim_id_est_laborum." ) ); - } - - - /** - * Ensure that the php passed site of parameter values are not urldecoded - */ - public function testPatternUrlencoding() { - $router = new PathRouter; - $router->add( "/wiki/$1", array( 'title' => '%20:$1' ) ); - $matches = $router->parse( "/wiki/Foo" ); - $this->assertEquals( $matches, array( 'title' => '%20:Foo' ) ); - } - - /** - * Ensure that raw parameter values do not have any variable replacements or urldecoding - */ - public function testRawParamValue() { - $router = new PathRouter; - $router->add( "/wiki/$1", array( 'title' => array( 'value' => 'bar%20$1' ) ) ); - $matches = $router->parse( "/wiki/Foo" ); - $this->assertEquals( $matches, array( 'title' => 'bar%20$1' ) ); - } - -} diff --git a/tests/phpunit/includes/PreferencesTest.php b/tests/phpunit/includes/PreferencesTest.php deleted file mode 100644 index 0e123177..00000000 --- a/tests/phpunit/includes/PreferencesTest.php +++ /dev/null @@ -1,75 +0,0 @@ -prefUsers['noemail'] = new User; - - $this->prefUsers['notauth'] = new User; - $this->prefUsers['notauth'] - ->setEmail( 'noauth@example.org' ); - - $this->prefUsers['auth'] = new User; - $this->prefUsers['auth'] - ->setEmail( 'noauth@example.org' ); - $this->prefUsers['auth'] - ->setEmailAuthenticationTimestamp( 1330946623 ); - - $this->context = new RequestContext; - $this->context->setTitle( Title::newFromText('PreferencesTest') ); - - //some tests depends on email setting - $wgEnableEmail = true; - } - - /** - * Placeholder to verify bug 34302 - * @covers Preferences::profilePreferences - */ - function testEmailFieldsWhenUserHasNoEmail() { - $prefs = $this->prefsFor( 'noemail' ); - $this->assertArrayHasKey( 'cssclass', - $prefs['emailaddress'] - ); - $this->assertEquals( 'mw-email-none', $prefs['emailaddress']['cssclass'] ); - } - /** - * Placeholder to verify bug 34302 - * @covers Preferences::profilePreferences - */ - function testEmailFieldsWhenUserEmailNotAuthenticated() { - $prefs = $this->prefsFor( 'notauth' ); - $this->assertArrayHasKey( 'cssclass', - $prefs['emailaddress'] - ); - $this->assertEquals( 'mw-email-not-authenticated', $prefs['emailaddress']['cssclass'] ); - } - /** - * Placeholder to verify bug 34302 - * @covers Preferences::profilePreferences - */ - function testEmailFieldsWhenUserEmailIsAuthenticated() { - $prefs = $this->prefsFor( 'auth' ); - $this->assertArrayHasKey( 'cssclass', - $prefs['emailaddress'] - ); - $this->assertEquals( 'mw-email-authenticated', $prefs['emailaddress']['cssclass'] ); - } - - /** Helper */ - function prefsFor( $user_key ) { - $preferences = array(); - Preferences::profilePreferences( - $this->prefUsers[$user_key] - , $this->context - , $preferences - ); - return $preferences; - } -} diff --git a/tests/phpunit/includes/Providers.php b/tests/phpunit/includes/Providers.php deleted file mode 100644 index f451f8a0..00000000 --- a/tests/phpunit/includes/Providers.php +++ /dev/null @@ -1,44 +0,0 @@ -title = Title::newFromText( 'SomeTitle' ); - $this->target = Title::newFromText( 'TestTarget' ); - $this->user = User::newFromName( 'UserName' ); - - $this->user_comment = ''; - $this->context = RequestContext::newExtraneousContext( $this->title ); - } - - /** - * The testIrcMsgForAction* tests are supposed to cover the hacky - * LogFormatter::getIRCActionText / bug 34508 - * - * Third parties bots listen to those messages. They are clever enough - * to fetch the i18n messages from the wiki and then analyze the IRC feed - * to reverse engineer the $1, $2 messages. - * One thing bots can not detect is when MediaWiki change the meaning of - * a message like what happened when we deployed 1.19. $1 became the user - * performing the action which broke basically all bots around. - * - * Should cover the following log actions (which are most commonly used by bots): - * - block/block - * - block/unblock - * - delete/delete - * - delete/restore - * - newusers/create - * - newusers/create2 - * - newusers/autocreate - * - move/move - * - move/move_redir - * - protect/protect - * - protect/modifyprotect - * - protect/unprotect - * - upload/upload - * - * As well as the following Auto Edit Summaries: - * - blank - * - replace - * - rollback - * - undo - */ - - /** - * @covers LogFormatter::getIRCActionText - */ - function testIrcMsgForLogTypeBlock() { - # block/block - $this->assertIRCComment( - $this->context->msg( 'blocklogentry', 'SomeTitle' )->plain() . ': ' . $this->user_comment, - 'block', 'block', - array(), - $this->user_comment - ); - # block/unblock - $this->assertIRCComment( - $this->context->msg( 'unblocklogentry', 'SomeTitle' )->plain() . ': ' . $this->user_comment, - 'block', 'unblock', - array(), - $this->user_comment - ); - } - - /** - * @covers LogFormatter::getIRCActionText - */ - function testIrcMsgForLogTypeDelete() { - # delete/delete - $this->assertIRCComment( - $this->context->msg( 'deletedarticle', 'SomeTitle' )->plain() . ': ' . $this->user_comment, - 'delete', 'delete', - array(), - $this->user_comment - ); - - # delete/restore - $this->assertIRCComment( - $this->context->msg( 'undeletedarticle', 'SomeTitle' )->plain() . ': ' . $this->user_comment, - 'delete', 'restore', - array(), - $this->user_comment - ); - } - - /** - * @covers LogFormatter::getIRCActionText - */ - function testIrcMsgForLogTypeNewusers() { - $this->assertIRCComment( - 'New user account', - 'newusers', 'newusers', - array() - ); - $this->assertIRCComment( - 'New user account', - 'newusers', 'create', - array() - ); - $this->assertIRCComment( - 'created new account SomeTitle', - 'newusers', 'create2', - array() - ); - $this->assertIRCComment( - 'Account created automatically', - 'newusers', 'autocreate', - array() - ); - } - - /** - * @covers LogFormatter::getIRCActionText - */ - function testIrcMsgForLogTypeMove() { - $move_params = array( - '4::target' => $this->target->getPrefixedText(), - '5::noredir' => 0, - ); - - # move/move - $this->assertIRCComment( - $this->context->msg( '1movedto2', 'SomeTitle', 'TestTarget' )->plain() . ': ' . $this->user_comment, - 'move', 'move', - $move_params, - $this->user_comment - ); - - # move/move_redir - $this->assertIRCComment( - $this->context->msg( '1movedto2_redir', 'SomeTitle', 'TestTarget' )->plain() . ': ' . $this->user_comment, - 'move', 'move_redir', - $move_params, - $this->user_comment - ); - } - - /** - * @covers LogFormatter::getIRCActionText - */ - function testIrcMsgForLogTypePatrol() { - # patrol/patrol - $this->assertIRCComment( - $this->context->msg( 'patrol-log-line', 'revision 777', '[[SomeTitle]]', '' )->plain(), - 'patrol', 'patrol', - array( - '4::curid' => '777', - '5::previd' => '666', - '6::auto' => 0, - ) - ); - } - - /** - * @covers LogFormatter::getIRCActionText - */ - function testIrcMsgForLogTypeProtect() { - $protectParams = array( - '[edit=sysop] (indefinite) ‎[move=sysop] (indefinite)' - ); - - # protect/protect - $this->assertIRCComment( - $this->context->msg( 'protectedarticle', 'SomeTitle ' . $protectParams[0] )->plain() . ': ' . $this->user_comment, - 'protect', 'protect', - $protectParams, - $this->user_comment - ); - - # protect/unprotect - $this->assertIRCComment( - $this->context->msg( 'unprotectedarticle', 'SomeTitle' )->plain() . ': ' . $this->user_comment, - 'protect', 'unprotect', - array(), - $this->user_comment - ); - - # protect/modify - $this->assertIRCComment( - $this->context->msg( 'modifiedarticleprotection', 'SomeTitle ' . $protectParams[0] )->plain() . ': ' . $this->user_comment, - 'protect', 'modify', - $protectParams, - $this->user_comment - ); - } - - /** - * @covers LogFormatter::getIRCActionText - */ - function testIrcMsgForLogTypeUpload() { - # upload/upload - $this->assertIRCComment( - $this->context->msg( 'uploadedimage', 'SomeTitle' )->plain() . ': ' . $this->user_comment, - 'upload', 'upload', - array(), - $this->user_comment - ); - - # upload/overwrite - $this->assertIRCComment( - $this->context->msg( 'overwroteimage', 'SomeTitle' )->plain() . ': ' . $this->user_comment, - 'upload', 'overwrite', - array(), - $this->user_comment - ); - } - - /** - * @todo: Emulate these edits somehow and extract - * raw edit summary from RecentChange object - * -- - - function testIrcMsgForBlankingAES() { - // $this->context->msg( 'autosumm-blank', .. ); - } - - function testIrcMsgForReplaceAES() { - // $this->context->msg( 'autosumm-replace', .. ); - } - - function testIrcMsgForRollbackAES() { - // $this->context->msg( 'revertpage', .. ); - } - - function testIrcMsgForUndoAES() { - // $this->context->msg( 'undo-summary', .. ); - } - - * -- - */ - - /** - * @param $expected String Expected IRC text without colors codes - * @param $type String Log type (move, delete, suppress, patrol ...) - * @param $action String A log type action - * @param $comment String (optional) A comment for the log action - * @param $msg String (optional) A message for PHPUnit :-) - */ - function assertIRCComment( $expected, $type, $action, $params, $comment = null, $msg = '' ) { - - $logEntry = new ManualLogEntry( $type, $action ); - $logEntry->setPerformer( $this->user ); - $logEntry->setTarget( $this->title ); - if ( $comment !== null ) { - $logEntry->setComment( $comment ); - } - $logEntry->setParameters( $params ); - - $formatter = LogFormatter::newFromEntry( $logEntry ); - $formatter->setContext( $this->context ); - - // Apply the same transformation as done in RecentChange::getIRCLine for rc_comment - $ircRcComment = RecentChange::cleanupForIRC( $formatter->getIRCActionComment() ); - - $this->assertEquals( - $expected, - $ircRcComment, - $msg - ); - } - -} diff --git a/tests/phpunit/includes/ResourceLoaderTest.php b/tests/phpunit/includes/ResourceLoaderTest.php deleted file mode 100644 index ab704839..00000000 --- a/tests/phpunit/includes/ResourceLoaderTest.php +++ /dev/null @@ -1,91 +0,0 @@ -assertTrue( self::$resourceLoaderRegisterModulesHook ); - return $resourceLoader; - } - - /** - * @dataProvider provideValidModules - * @depends testCreatingNewResourceLoaderCallsRegistrationHook - * @covers ResourceLoader::register - * @covers ResourceLoader::getModule - */ - public function testRegisteredValidModulesAreAccessible( - $name, ResourceLoaderModule $module, ResourceLoader $resourceLoader - ) { - $resourceLoader->register( $name, $module ); - $this->assertEquals( $module, $resourceLoader->getModule( $name ) ); - } - - /** - * @dataProvider providePackedModules - */ - public function testMakePackedModulesString( $desc, $modules, $packed ) { - $this->assertEquals( $packed, ResourceLoader::makePackedModulesString( $modules ), $desc ); - } - - /** - * @dataProvider providePackedModules - */ - public function testexpandModuleNames( $desc, $modules, $packed ) { - $this->assertEquals( $modules, ResourceLoaderContext::expandModuleNames( $packed ), $desc ); - } - - public function providePackedModules() { - return array( - array( - 'Example from makePackedModulesString doc comment', - array( 'foo.bar', 'foo.baz', 'bar.baz', 'bar.quux' ), - 'foo.bar,baz|bar.baz,quux', - ), - array( - 'Example from expandModuleNames doc comment', - array( 'jquery.foo', 'jquery.bar', 'jquery.ui.baz', 'jquery.ui.quux' ), - 'jquery.foo,bar|jquery.ui.baz,quux', - ), - array( - 'Regression fixed in r88706 with dotless names', - array( 'foo', 'bar', 'baz' ), - 'foo,bar,baz', - ) - ); - } -} - -/* Stubs */ - -class ResourceLoaderTestModule extends ResourceLoaderModule { } - -/* Hooks */ -global $wgHooks; -$wgHooks['ResourceLoaderRegisterModules'][] = 'ResourceLoaderTest::resourceLoaderRegisterModules'; diff --git a/tests/phpunit/includes/RevisionStorageTest.php b/tests/phpunit/includes/RevisionStorageTest.php deleted file mode 100644 index 8a7facec..00000000 --- a/tests/phpunit/includes/RevisionStorageTest.php +++ /dev/null @@ -1,408 +0,0 @@ -tablesUsed = array_merge( $this->tablesUsed, - array( 'page', - 'revision', - 'text', - - 'recentchanges', - 'logging', - - 'page_props', - 'pagelinks', - 'categorylinks', - 'langlinks', - 'externallinks', - 'imagelinks', - 'templatelinks', - 'iwlinks' ) ); - } - - public function setUp() { - if ( !$this->the_page ) { - $this->the_page = $this->createPage( 'RevisionStorageTest_the_page', "just a dummy page" ); - } - } - - protected function makeRevision( $props = null ) { - if ( $props === null ) $props = array(); - - if ( !isset( $props['content'] ) && !isset( $props['text'] ) ) $props['text'] = 'Lorem Ipsum'; - if ( !isset( $props['comment'] ) ) $props['comment'] = 'just a test'; - if ( !isset( $props['page'] ) ) $props['page'] = $this->the_page->getId(); - - $rev = new Revision( $props ); - - $dbw = wfgetDB( DB_MASTER ); - $rev->insertOn( $dbw ); - - return $rev; - } - - protected function createPage( $page, $text, $model = null ) { - if ( is_string( $page ) ) $page = Title::newFromText( $page ); - if ( $page instanceof Title ) $page = new WikiPage( $page ); - - if ( $page->exists() ) { - $page->doDeleteArticle( "done" ); - } - - $page->doEdit( $text, "testing", EDIT_NEW ); - - return $page; - } - - protected function assertRevEquals( Revision $orig, Revision $rev = null ) { - $this->assertNotNull( $rev, 'missing revision' ); - - $this->assertEquals( $orig->getId(), $rev->getId() ); - $this->assertEquals( $orig->getPage(), $rev->getPage() ); - $this->assertEquals( $orig->getTimestamp(), $rev->getTimestamp() ); - $this->assertEquals( $orig->getUser(), $rev->getUser() ); - $this->assertEquals( $orig->getSha1(), $rev->getSha1() ); - } - - /** - * @covers Revision::__construct - */ - public function testConstructFromRow() - { - $orig = $this->makeRevision(); - - $dbr = wfgetDB( DB_SLAVE ); - $res = $dbr->select( 'revision', '*', array( 'rev_id' => $orig->getId() ) ); - $this->assertTrue( is_object( $res ), 'query failed' ); - - $row = $res->fetchObject(); - $res->free(); - - $rev = new Revision( $row ); - - $this->assertRevEquals( $orig, $rev ); - } - - /** - * @covers Revision::newFromRow - */ - public function testNewFromRow() - { - $orig = $this->makeRevision(); - - $dbr = wfgetDB( DB_SLAVE ); - $res = $dbr->select( 'revision', '*', array( 'rev_id' => $orig->getId() ) ); - $this->assertTrue( is_object( $res ), 'query failed' ); - - $row = $res->fetchObject(); - $res->free(); - - $rev = Revision::newFromRow( $row ); - - $this->assertRevEquals( $orig, $rev ); - } - - - /** - * @covers Revision::newFromArchiveRow - */ - public function testNewFromArchiveRow() - { - $page = $this->createPage( 'RevisionStorageTest_testNewFromArchiveRow', 'Lorem Ipsum' ); - $orig = $page->getRevision(); - $page->doDeleteArticle( 'test Revision::newFromArchiveRow' ); - - $dbr = wfgetDB( DB_SLAVE ); - $res = $dbr->select( 'archive', '*', array( 'ar_rev_id' => $orig->getId() ) ); - $this->assertTrue( is_object( $res ), 'query failed' ); - - $row = $res->fetchObject(); - $res->free(); - - $rev = Revision::newFromArchiveRow( $row ); - - $this->assertRevEquals( $orig, $rev ); - } - - /** - * @covers Revision::newFromId - */ - public function testNewFromId() - { - $orig = $this->makeRevision(); - - $rev = Revision::newFromId( $orig->getId() ); - - $this->assertRevEquals( $orig, $rev ); - } - - /** - * @covers Revision::fetchRevision - */ - public function testFetchRevision() - { - $page = $this->createPage( 'RevisionStorageTest_testFetchRevision', 'one' ); - $id1 = $page->getRevision()->getId(); - - $page->doEdit( 'two', 'second rev' ); - $id2 = $page->getRevision()->getId(); - - $res = Revision::fetchRevision( $page->getTitle() ); - - #note: order is unspecified - $rows = array(); - while ( ( $row = $res->fetchObject() ) ) { - $rows[ $row->rev_id ]= $row; - } - - $row = $res->fetchObject(); - $this->assertEquals( 1, count($rows), 'expected exactly one revision' ); - $this->assertArrayHasKey( $id2, $rows, 'missing revision with id ' . $id2 ); - } - - /** - * @covers Revision::selectFields - */ - public function testSelectFields() - { - $fields = Revision::selectFields(); - - $this->assertTrue( in_array( 'rev_id', $fields ), 'missing rev_id in list of fields'); - $this->assertTrue( in_array( 'rev_page', $fields ), 'missing rev_page in list of fields'); - $this->assertTrue( in_array( 'rev_timestamp', $fields ), 'missing rev_timestamp in list of fields'); - $this->assertTrue( in_array( 'rev_user', $fields ), 'missing rev_user in list of fields'); - } - - /** - * @covers Revision::getPage - */ - public function testGetPage() - { - $page = $this->the_page; - - $orig = $this->makeRevision( array( 'page' => $page->getId() ) ); - $rev = Revision::newFromId( $orig->getId() ); - - $this->assertEquals( $page->getId(), $rev->getPage() ); - } - - /** - * @covers Revision::getText - */ - public function testGetText() - { - $orig = $this->makeRevision( array( 'text' => 'hello hello.' ) ); - $rev = Revision::newFromId( $orig->getId() ); - - $this->assertEquals( 'hello hello.', $rev->getText() ); - } - - /** - * @covers Revision::revText - */ - public function testRevText() - { - $this->hideDeprecated( 'Revision::revText' ); - $orig = $this->makeRevision( array( 'text' => 'hello hello rev.' ) ); - $rev = Revision::newFromId( $orig->getId() ); - - $this->assertEquals( 'hello hello rev.', $rev->revText() ); - } - - /** - * @covers Revision::getRawText - */ - public function testGetRawText() - { - $orig = $this->makeRevision( array( 'text' => 'hello hello raw.' ) ); - $rev = Revision::newFromId( $orig->getId() ); - - $this->assertEquals( 'hello hello raw.', $rev->getRawText() ); - } - /** - * @covers Revision::isCurrent - */ - public function testIsCurrent() - { - $page = $this->createPage( 'RevisionStorageTest_testIsCurrent', 'Lorem Ipsum' ); - $rev1 = $page->getRevision(); - - # @todo: find out if this should be true - # $this->assertTrue( $rev1->isCurrent() ); - - $rev1x = Revision::newFromId( $rev1->getId() ); - $this->assertTrue( $rev1x->isCurrent() ); - - $page->doEdit( 'Bla bla', 'second rev' ); - $rev2 = $page->getRevision(); - - # @todo: find out if this should be true - # $this->assertTrue( $rev2->isCurrent() ); - - $rev1x = Revision::newFromId( $rev1->getId() ); - $this->assertFalse( $rev1x->isCurrent() ); - - $rev2x = Revision::newFromId( $rev2->getId() ); - $this->assertTrue( $rev2x->isCurrent() ); - } - - /** - * @covers Revision::getPrevious - */ - public function testGetPrevious() - { - $page = $this->createPage( 'RevisionStorageTest_testGetPrevious', 'Lorem Ipsum testGetPrevious' ); - $rev1 = $page->getRevision(); - - $this->assertNull( $rev1->getPrevious() ); - - $page->doEdit( 'Bla bla', 'second rev testGetPrevious' ); - $rev2 = $page->getRevision(); - - $this->assertNotNull( $rev2->getPrevious() ); - $this->assertEquals( $rev1->getId(), $rev2->getPrevious()->getId() ); - } - - /** - * @covers Revision::getNext - */ - public function testGetNext() - { - $page = $this->createPage( 'RevisionStorageTest_testGetNext', 'Lorem Ipsum testGetNext' ); - $rev1 = $page->getRevision(); - - $this->assertNull( $rev1->getNext() ); - - $page->doEdit( 'Bla bla', 'second rev testGetNext' ); - $rev2 = $page->getRevision(); - - $this->assertNotNull( $rev1->getNext() ); - $this->assertEquals( $rev2->getId(), $rev1->getNext()->getId() ); - } - - /** - * @covers Revision::newNullRevision - */ - public function testNewNullRevision() - { - $page = $this->createPage( 'RevisionStorageTest_testNewNullRevision', 'some testing text' ); - $orig = $page->getRevision(); - - $dbw = wfGetDB( DB_MASTER ); - $rev = Revision::newNullRevision( $dbw, $page->getId(), 'a null revision', false ); - - $this->assertNotEquals( $orig->getId(), $rev->getId(), 'new null revision shold have a different id from the original revision' ); - $this->assertEquals( $orig->getTextId(), $rev->getTextId(), 'new null revision shold have the same text id as the original revision' ); - $this->assertEquals( 'some testing text', $rev->getText() ); - } - - public function dataUserWasLastToEdit() { - return array( - array( #0 - 3, true, # actually the last edit - ), - array( #1 - 2, true, # not the current edit, but still by this user - ), - array( #2 - 1, false, # edit by another user - ), - array( #3 - 0, false, # first edit, by this user, but another user edited in the mean time - ), - ); - } - - /** - * @dataProvider dataUserWasLastToEdit - */ - public function testUserWasLastToEdit( $sinceIdx, $expectedLast ) { - $userA = \User::newFromName( "RevisionStorageTest_userA" ); - $userB = \User::newFromName( "RevisionStorageTest_userB" ); - - if ( $userA->getId() === 0 ) { - $userA = \User::createNew( $userA->getName() ); - } - - if ( $userB->getId() === 0 ) { - $userB = \User::createNew( $userB->getName() ); - } - - $dbw = wfGetDB( DB_MASTER ); - $revisions = array(); - - // create revisions ----------------------------- - $page = WikiPage::factory( Title::newFromText( 'RevisionStorageTest_testUserWasLastToEdit' ) ); - - # zero - $revisions[0] = new Revision( array( - 'page' => $page->getId(), - 'timestamp' => '20120101000000', - 'user' => $userA->getId(), - 'text' => 'zero', - 'summary' => 'edit zero' - ) ); - $revisions[0]->insertOn( $dbw ); - - # one - $revisions[1] = new Revision( array( - 'page' => $page->getId(), - 'timestamp' => '20120101000100', - 'user' => $userA->getId(), - 'text' => 'one', - 'summary' => 'edit one' - ) ); - $revisions[1]->insertOn( $dbw ); - - # two - $revisions[2] = new Revision( array( - 'page' => $page->getId(), - 'timestamp' => '20120101000200', - 'user' => $userB->getId(), - 'text' => 'two', - 'summary' => 'edit two' - ) ); - $revisions[2]->insertOn( $dbw ); - - # three - $revisions[3] = new Revision( array( - 'page' => $page->getId(), - 'timestamp' => '20120101000300', - 'user' => $userA->getId(), - 'text' => 'three', - 'summary' => 'edit three' - ) ); - $revisions[3]->insertOn( $dbw ); - - # four - $revisions[4] = new Revision( array( - 'page' => $page->getId(), - 'timestamp' => '20120101000200', - 'user' => $userA->getId(), - 'text' => 'zero', - 'summary' => 'edit four' - ) ); - $revisions[4]->insertOn( $dbw ); - - // test it --------------------------------- - $since = $revisions[ $sinceIdx ]->getTimestamp(); - - $wasLast = Revision::userWasLastToEdit( $dbw, $page->getId(), $userA->getId(), $since ); - - $this->assertEquals( $expectedLast, $wasLast ); - } -} diff --git a/tests/phpunit/includes/RevisionTest.php b/tests/phpunit/includes/RevisionTest.php deleted file mode 100644 index d7654db9..00000000 --- a/tests/phpunit/includes/RevisionTest.php +++ /dev/null @@ -1,125 +0,0 @@ - false, - 'wgCompressRevisions' => false, - ); - foreach ( $globalSet as $var => $data ) { - $this->saveGlobals[$var] = $GLOBALS[$var]; - $GLOBALS[$var] = $data; - } - } - - function tearDown() { - foreach ( $this->saveGlobals as $var => $data ) { - $GLOBALS[$var] = $data; - } - } - - function testGetRevisionText() { - $row = new stdClass; - $row->old_flags = ''; - $row->old_text = 'This is a bunch of revision text.'; - $this->assertEquals( - 'This is a bunch of revision text.', - Revision::getRevisionText( $row ) ); - } - - function testGetRevisionTextGzip() { - if ( !function_exists( 'gzdeflate' ) ) { - $this->markTestSkipped( 'Gzip compression is not enabled (requires zlib).' ); - } else { - $row = new stdClass; - $row->old_flags = 'gzip'; - $row->old_text = gzdeflate( 'This is a bunch of revision text.' ); - $this->assertEquals( - 'This is a bunch of revision text.', - Revision::getRevisionText( $row ) ); - } - } - - function testGetRevisionTextUtf8Native() { - $row = new stdClass; - $row->old_flags = 'utf-8'; - $row->old_text = "Wiki est l'\xc3\xa9cole superieur !"; - $GLOBALS['wgLegacyEncoding'] = 'iso-8859-1'; - $this->assertEquals( - "Wiki est l'\xc3\xa9cole superieur !", - Revision::getRevisionText( $row ) ); - } - - function testGetRevisionTextUtf8Legacy() { - $row = new stdClass; - $row->old_flags = ''; - $row->old_text = "Wiki est l'\xe9cole superieur !"; - $GLOBALS['wgLegacyEncoding'] = 'iso-8859-1'; - $this->assertEquals( - "Wiki est l'\xc3\xa9cole superieur !", - Revision::getRevisionText( $row ) ); - } - - function testGetRevisionTextUtf8NativeGzip() { - if ( !function_exists( 'gzdeflate' ) ) { - $this->markTestSkipped( 'Gzip compression is not enabled (requires zlib).' ); - } else { - $row = new stdClass; - $row->old_flags = 'gzip,utf-8'; - $row->old_text = gzdeflate( "Wiki est l'\xc3\xa9cole superieur !" ); - $GLOBALS['wgLegacyEncoding'] = 'iso-8859-1'; - $this->assertEquals( - "Wiki est l'\xc3\xa9cole superieur !", - Revision::getRevisionText( $row ) ); - } - } - - function testGetRevisionTextUtf8LegacyGzip() { - if ( !function_exists( 'gzdeflate' ) ) { - $this->markTestSkipped( 'Gzip compression is not enabled (requires zlib).' ); - } else { - $row = new stdClass; - $row->old_flags = 'gzip'; - $row->old_text = gzdeflate( "Wiki est l'\xe9cole superieur !" ); - $GLOBALS['wgLegacyEncoding'] = 'iso-8859-1'; - $this->assertEquals( - "Wiki est l'\xc3\xa9cole superieur !", - Revision::getRevisionText( $row ) ); - } - } - - function testCompressRevisionTextUtf8() { - $row = new stdClass; - $row->old_text = "Wiki est l'\xc3\xa9cole superieur !"; - $row->old_flags = Revision::compressRevisionText( $row->old_text ); - $this->assertTrue( false !== strpos( $row->old_flags, 'utf-8' ), - "Flags should contain 'utf-8'" ); - $this->assertFalse( false !== strpos( $row->old_flags, 'gzip' ), - "Flags should not contain 'gzip'" ); - $this->assertEquals( "Wiki est l'\xc3\xa9cole superieur !", - $row->old_text, "Direct check" ); - $this->assertEquals( "Wiki est l'\xc3\xa9cole superieur !", - Revision::getRevisionText( $row ), "getRevisionText" ); - } - - function testCompressRevisionTextUtf8Gzip() { - $GLOBALS['wgCompressRevisions'] = true; - $row = new stdClass; - $row->old_text = "Wiki est l'\xc3\xa9cole superieur !"; - $row->old_flags = Revision::compressRevisionText( $row->old_text ); - $this->assertTrue( false !== strpos( $row->old_flags, 'utf-8' ), - "Flags should contain 'utf-8'" ); - $this->assertTrue( false !== strpos( $row->old_flags, 'gzip' ), - "Flags should contain 'gzip'" ); - $this->assertEquals( "Wiki est l'\xc3\xa9cole superieur !", - gzinflate( $row->old_text ), "Direct check" ); - $this->assertEquals( "Wiki est l'\xc3\xa9cole superieur !", - Revision::getRevisionText( $row ), "getRevisionText" ); - } -} - - diff --git a/tests/phpunit/includes/SampleTest.php b/tests/phpunit/includes/SampleTest.php deleted file mode 100644 index 59ba0a04..00000000 --- a/tests/phpunit/includes/SampleTest.php +++ /dev/null @@ -1,98 +0,0 @@ -assertEquals("Text", $title->__toString(), "Title creation"); - $this->assertEquals("Text", "Text", "Automatic string conversion"); - - $title = Title::newFromText("text", NS_MEDIA); - $this->assertEquals("Media:Text", $title->__toString(), "Title creation with namespace"); - - } - - /** - * If you want to run a the same test with a variety of data. use a data provider. - * see: http://www.phpunit.de/manual/3.4/en/writing-tests-for-phpunit.html - */ - public function provideTitles() { - return array( - array( 'Text', NS_MEDIA, 'Media:Text' ), - array( 'Text', null, 'Text' ), - array( 'text', null, 'Text' ), - array( 'Text', NS_USER, 'User:Text' ), - array( 'Photo.jpg', NS_FILE, 'File:Photo.jpg' ) - ); - } - - /** - * @dataProvider provideTitles - * See http://www.phpunit.de/manual/3.4/en/appendixes.annotations.html#appendixes.annotations.dataProvider - */ - public function testCreateBasicListOfTitles($titleName, $ns, $text) { - $title = Title::newFromText($titleName, $ns); - $this->assertEquals($text, "$title", "see if '$titleName' matches '$text'"); - } - - public function testSetUpMainPageTitleForNextTest() { - $title = Title::newMainPage(); - $this->assertEquals("Main Page", "$title", "Test initial creation of a title"); - - return $title; - } - - /** - * Instead of putting a bunch of tests in a single test method, - * you should put only one or two tests in each test method. This - * way, the test method names can remain descriptive. - * - * If you want to make tests depend on data created in another - * method, you can create dependencies feed whatever you return - * from the dependant method (e.g. testInitialCreation in this - * example) as arguments to the next method (e.g. $title in - * testTitleDepends is whatever testInitialCreatiion returned.) - */ - /** - * @depends testSetUpMainPageTitleForNextTest - * See http://www.phpunit.de/manual/3.4/en/appendixes.annotations.html#appendixes.annotations.depends - */ - public function testCheckMainPageTitleIsConsideredLocal( $title ) { - $this->assertTrue( $title->isLocal() ); - } - - /** - * @expectedException MWException object - * See http://www.phpunit.de/manual/3.4/en/appendixes.annotations.html#appendixes.annotations.expectedException - */ - function testTitleObjectFromObject() { - $title = Title::newFromText( Title::newFromText( "test" ) ); - $this->assertEquals( "Test", $title->isLocal() ); - } -} - diff --git a/tests/phpunit/includes/SanitizerTest.php b/tests/phpunit/includes/SanitizerTest.php deleted file mode 100644 index 66af2581..00000000 --- a/tests/phpunit/includes/SanitizerTest.php +++ /dev/null @@ -1,162 +0,0 @@ -assertEquals( - "\xc3\xa9cole", - Sanitizer::decodeCharReferences( 'école' ), - 'decode named entities' - ); - } - - function testDecodeNumericEntities() { - $this->assertEquals( - "\xc4\x88io bonas dans l'\xc3\xa9cole!", - Sanitizer::decodeCharReferences( "Ĉio bonas dans l'école!" ), - 'decode numeric entities' - ); - } - - function testDecodeMixedEntities() { - $this->assertEquals( - "\xc4\x88io bonas dans l'\xc3\xa9cole!", - Sanitizer::decodeCharReferences( "Ĉio bonas dans l'école!" ), - 'decode mixed numeric/named entities' - ); - } - - function testDecodeMixedComplexEntities() { - $this->assertEquals( - "\xc4\x88io bonas dans l'\xc3\xa9cole! (mais pas Ĉio dans l'école)", - Sanitizer::decodeCharReferences( - "Ĉio bonas dans l'école! (mais pas &#x108;io dans l'&eacute;cole)" - ), - 'decode mixed complex entities' - ); - } - - function testInvalidAmpersand() { - $this->assertEquals( - 'a & b', - Sanitizer::decodeCharReferences( 'a & b' ), - 'Invalid ampersand' - ); - } - - function testInvalidEntities() { - $this->assertEquals( - '&foo;', - Sanitizer::decodeCharReferences( '&foo;' ), - 'Invalid named entity' - ); - } - - function testInvalidNumberedEntities() { - $this->assertEquals( UTF8_REPLACEMENT, Sanitizer::decodeCharReferences( "�" ), 'Invalid numbered entity' ); - } - - function testSelfClosingTag() { - $GLOBALS['wgUseTidy'] = false; - $this->assertEquals( - '
Hello world
', - Sanitizer::removeHTMLtags( '
Hello world
' ), - 'Self-closing closing div' - ); - } - - function testDecodeTagAttributes() { - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo=bar' ), array( 'foo' => 'bar' ), 'Unquoted attribute' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( ' foo = bar ' ), array( 'foo' => 'bar' ), 'Spaced attribute' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo="bar"' ), array( 'foo' => 'bar' ), 'Double-quoted attribute' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo=\'bar\'' ), array( 'foo' => 'bar' ), 'Single-quoted attribute' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo=\'bar\' baz="foo"' ), array( 'foo' => 'bar', 'baz' => 'foo' ), 'Several attributes' ); - - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo=\'bar\' baz="foo"' ), array( 'foo' => 'bar', 'baz' => 'foo' ), 'Several attributes' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo=\'bar\' baz="foo"' ), array( 'foo' => 'bar', 'baz' => 'foo' ), 'Several attributes' ); - - $this->assertEquals( Sanitizer::decodeTagAttributes( ':foo=\'bar\'' ), array( ':foo' => 'bar' ), 'Leading :' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( '_foo=\'bar\'' ), array( '_foo' => 'bar' ), 'Leading _' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( 'Foo=\'bar\'' ), array( 'foo' => 'bar' ), 'Leading capital' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( 'FOO=BAR' ), array( 'foo' => 'BAR' ), 'Attribute keys are normalized to lowercase' ); - - # Invalid beginning - $this->assertEquals( Sanitizer::decodeTagAttributes( '-foo=bar' ), array(), 'Leading - is forbidden' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( '.foo=bar' ), array(), 'Leading . is forbidden' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo-bar=bar' ), array( 'foo-bar' => 'bar' ), 'A - is allowed inside the attribute' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo-=bar' ), array( 'foo-' => 'bar' ), 'A - is allowed inside the attribute' ); - - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo.bar=baz' ), array( 'foo.bar' => 'baz' ), 'A . is allowed inside the attribute' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo.=baz' ), array( 'foo.' => 'baz' ), 'A . is allowed as last character' ); - - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo6=baz' ), array( 'foo6' => 'baz' ), 'Numbers are allowed' ); - - # This bit is more relaxed than XML rules, but some extensions use it, like ProofreadPage (see bug 27539) - $this->assertEquals( Sanitizer::decodeTagAttributes( '1foo=baz' ), array( '1foo' => 'baz' ), 'Leading numbers are allowed' ); - - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo$=baz' ), array(), 'Symbols are not allowed' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo@=baz' ), array(), 'Symbols are not allowed' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo~=baz' ), array(), 'Symbols are not allowed' ); - - - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo=1[#^`*%w/(' ), array( 'foo' => '1[#^`*%w/(' ), 'All kind of characters are allowed as values' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo="1[#^`*%\'w/("' ), array( 'foo' => '1[#^`*%\'w/(' ), 'Double quotes are allowed if quoted by single quotes' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo=\'1[#^`*%"w/(\'' ), array( 'foo' => '1[#^`*%"w/(' ), 'Single quotes are allowed if quoted by double quotes' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo=&"' ), array( 'foo' => '&"' ), 'Special chars can be provided as entities' ); - $this->assertEquals( Sanitizer::decodeTagAttributes( 'foo=&foobar;' ), array( 'foo' => '&foobar;' ), 'Entity-like items are accepted' ); - } - - /** - * @dataProvider provideDeprecatedAttributes - */ - function testDeprecatedAttributesUnaltered( $inputAttr, $inputEl ) { - $this->assertEquals( " $inputAttr", Sanitizer::fixTagAttributes( $inputAttr, $inputEl ) ); - } - - public static function provideDeprecatedAttributes() { - return array( - array( 'clear="left"', 'br' ), - array( 'clear="all"', 'br' ), - array( 'width="100"', 'td' ), - array( 'nowrap="true"', 'td' ), - array( 'nowrap=""', 'td' ), - array( 'align="right"', 'td' ), - array( 'align="center"', 'table' ), - array( 'align="left"', 'tr' ), - array( 'align="center"', 'div' ), - array( 'align="left"', 'h1' ), - array( 'align="left"', 'span' ), - ); - } - - /** - * @dataProvider provideCssCommentsFixtures - */ - function testCssCommentsChecking( $expected, $css, $message = '' ) { - $this->assertEquals( - $expected, - Sanitizer::checkCss( $css ), - $message - ); - } - - function provideCssCommentsFixtures() { - /** array( , , [message] ) */ - return array( - array( ' ', '/**/' ), - array( ' ', '/****/' ), - array( ' ', '/* comment */' ), - array( ' ', "\\2f\\2a foo \\2a\\2f", - 'Backslash-escaped comments must be stripped (bug 28450)' ), - array( '', '/* unfinished comment structure', - 'Remove anything after a comment-start token' ), - array( '', "\\2f\\2a unifinished comment'", - 'Remove anything after a backslash-escaped comment-start token' ), - ); - } -} - diff --git a/tests/phpunit/includes/SanitizerValidateEmailTest.php b/tests/phpunit/includes/SanitizerValidateEmailTest.php deleted file mode 100644 index 14d799cf..00000000 --- a/tests/phpunit/includes/SanitizerValidateEmailTest.php +++ /dev/null @@ -1,79 +0,0 @@ -assertEquals( - $expected, - Sanitizer::validateEmail( $addr ), - $msg - ); - } - private function valid( $addr, $msg = '' ) { - $this->checkEmail( $addr, true, $msg ); - } - private function invalid( $addr, $msg = '' ) { - $this->checkEmail( $addr, false, $msg ); - } - - function testEmailWellKnownUserAtHostDotTldAreValid() { - $this->valid( 'user@example.com' ); - $this->valid( 'user@example.museum' ); - } - function testEmailWithUpperCaseCharactersAreValid() { - $this->valid( 'USER@example.com' ); - $this->valid( 'user@EXAMPLE.COM' ); - $this->valid( 'user@Example.com' ); - $this->valid( 'USER@eXAMPLE.com' ); - } - function testEmailWithAPlusInUserName() { - $this->valid( 'user+sub@example.com' ); - $this->valid( 'user+@example.com' ); - } - function testEmailDoesNotNeedATopLevelDomain() { - $this->valid( "user@localhost" ); - $this->valid( "FooBar@localdomain" ); - $this->valid( "nobody@mycompany" ); - } - function testEmailWithWhiteSpacesBeforeOrAfterAreInvalids() { - $this->invalid( " user@host.com" ); - $this->invalid( "user@host.com " ); - $this->invalid( "\tuser@host.com" ); - $this->invalid( "user@host.com\t" ); - } - function testEmailWithWhiteSpacesAreInvalids() { - $this->invalid( "User user@host" ); - $this->invalid( "first last@mycompany" ); - $this->invalid( "firstlast@my company" ); - } - // bug 26948 : comma were matched by an incorrect regexp range - function testEmailWithCommasAreInvalids() { - $this->invalid( "user,foo@example.org" ); - $this->invalid( "userfoo@ex,ample.org" ); - } - function testEmailWithHyphens() { - $this->valid( "user-foo@example.org" ); - $this->valid( "userfoo@ex-ample.org" ); - } - function testEmailDomainCanNotBeginWithDot() { - $this->invalid( "user@." ); - $this->invalid( "user@.localdomain" ); - $this->invalid( "user@localdomain." ); - $this->valid( "user.@localdomain" ); - $this->valid( ".@localdomain" ); - $this->invalid( ".@a............" ); - } - function testEmailWithFunnyCharacters() { - $this->valid( "\$user!ex{this}@123.com" ); - } - function testEmailTopLevelDomainCanBeNumerical() { - $this->valid( "user@example.1234" ); - } - function testEmailWithoutAtSignIsInvalid() { - $this->invalid( 'useràexample.com' ); - } - function testEmailWithOneCharacterDomainIsValid() { - $this->valid( 'user@a' ); - } -} diff --git a/tests/phpunit/includes/SeleniumConfigurationTest.php b/tests/phpunit/includes/SeleniumConfigurationTest.php deleted file mode 100644 index 8589c188..00000000 --- a/tests/phpunit/includes/SeleniumConfigurationTest.php +++ /dev/null @@ -1,228 +0,0 @@ - '*firefox', - 'iexplorer' => '*iexploreproxy', - 'chrome' => '*chrome' - ); - /** - * Array of expected selenium settings from $testConfig0 - */ - private $testSettings0 = array( - 'host' => 'localhost', - 'port' => 'foobarr', - 'wikiUrl' => 'http://localhost/deployment', - 'username' => 'xxxxxxx', - 'userPassword' => '', - 'testBrowser' => 'chrome', - 'startserver' => null, - 'stopserver' => null, - 'seleniumserverexecpath' => null, - 'jUnitLogFile' => null, - 'runAgainstGrid' => null - ); - /** - * Array of expected testSuites from $testConfig0 - */ - private $testSuites0 = array( - 'SimpleSeleniumTestSuite' => 'tests/selenium/SimpleSeleniumTestSuite.php', - 'TestSuiteName' => 'testSuitePath' - ); - - - /** - * Another sample selenium settings file contents - */ - private $testConfig1 = -' -[SeleniumSettings] -host = "localhost" -testBrowser = "firefox" -'; - /** - * Expected browsers from $testConfig1 - */ - private $testBrowsers1 = null; - /** - * Expected selenium settings from $testConfig1 - */ - private $testSettings1 = array( - 'host' => 'localhost', - 'port' => null, - 'wikiUrl' => null, - 'username' => null, - 'userPassword' => null, - 'testBrowser' => 'firefox', - 'startserver' => null, - 'stopserver' => null, - 'seleniumserverexecpath' => null, - 'jUnitLogFile' => null, - 'runAgainstGrid' => null - ); - /** - * Expected test suites from $testConfig1 - */ - private $testSuites1 = null; - - - public function setUp() { - if ( !defined( 'SELENIUMTEST' ) ) { - define( 'SELENIUMTEST', true ); - } - } - - /** - * Clean up the temporary file used to store the selenium settings. - */ - public function tearDown() { - if ( strlen( $this->tempFileName ) > 0 ) { - unlink( $this->tempFileName ); - unset( $this->tempFileName ); - } - parent::tearDown(); - } - - /** - * @expectedException MWException - * @group SeleniumFramework - */ - public function testErrorOnIncorrectConfigFile() { - $seleniumSettings = array(); - $seleniumBrowsers = array(); - $seleniumTestSuites = array(); - - SeleniumConfig::getSeleniumSettings($seleniumSettings, - $seleniumBrowsers, - $seleniumTestSuites, - "Some_fake_settings_file.ini" ); - - } - - /** - * @expectedException MWException - * @group SeleniumFramework - */ - public function testErrorOnMissingConfigFile() { - $seleniumSettings = array(); - $seleniumBrowsers = array(); - $seleniumTestSuites = array(); - global $wgSeleniumConfigFile; - $wgSeleniumConfigFile = ''; - SeleniumConfig::getSeleniumSettings($seleniumSettings, - $seleniumBrowsers, - $seleniumTestSuites); - } - - /** - * @group SeleniumFramework - */ - public function testUsesGlobalVarForConfigFile() { - $seleniumSettings = array(); - $seleniumBrowsers = array(); - $seleniumTestSuites = array(); - global $wgSeleniumConfigFile; - $this->writeToTempFile( $this->testConfig0 ); - $wgSeleniumConfigFile = $this->tempFileName; - SeleniumConfig::getSeleniumSettings($seleniumSettings, - $seleniumBrowsers, - $seleniumTestSuites); - $this->assertEquals($seleniumSettings, $this->testSettings0 , - 'The selenium settings should have been read from the file defined in $wgSeleniumConfigFile' - ); - $this->assertEquals($seleniumBrowsers, $this->testBrowsers0, - 'The available browsers should have been read from the file defined in $wgSeleniumConfigFile' - ); - $this->assertEquals($seleniumTestSuites, $this->testSuites0, - 'The test suites should have been read from the file defined in $wgSeleniumConfigFile' - ); - } - - /** - * @group SeleniumFramework - * @dataProvider sampleConfigs - */ - public function testgetSeleniumSettings($sampleConfig, $expectedSettings, $expectedBrowsers, $expectedSuites ) { - $this->writeToTempFile( $sampleConfig ); - $seleniumSettings = array(); - $seleniumBrowsers = array(); - $seleniumTestSuites = null; - - SeleniumConfig::getSeleniumSettings($seleniumSettings, - $seleniumBrowsers, - $seleniumTestSuites, - $this->tempFileName ); - - $this->assertEquals($seleniumSettings, $expectedSettings, - "The selenium settings for the following test configuration was not retrieved correctly" . $sampleConfig - ); - $this->assertEquals($seleniumBrowsers, $expectedBrowsers, - "The available browsers for the following test configuration was not retrieved correctly" . $sampleConfig - ); - $this->assertEquals($seleniumTestSuites, $expectedSuites, - "The test suites for the following test configuration was not retrieved correctly" . $sampleConfig - ); - - - } - - /** - * create a temp file and write text to it. - * @param $testToWrite the text to write to the temp file - */ - private function writeToTempFile($textToWrite) { - $this->tempFileName = tempnam(sys_get_temp_dir(), 'test_settings.'); - $tempFile = fopen( $this->tempFileName, "w" ); - fwrite($tempFile , $textToWrite); - fclose($tempFile); - } - - /** - * Returns an array containing: - * The contents of the selenium cingiguration ini file - * The expected selenium configuration array that getSeleniumSettings should return - * The expected available browsers array that getSeleniumSettings should return - * The expected test suites arrya that getSeleniumSettings should return - */ - public function sampleConfigs() { - return array( - array($this->testConfig0, $this->testSettings0, $this->testBrowsers0, $this->testSuites0 ), - array($this->testConfig1, $this->testSettings1, $this->testBrowsers1, $this->testSuites1 ) - ); - } - - -} diff --git a/tests/phpunit/includes/SiteConfigurationTest.php b/tests/phpunit/includes/SiteConfigurationTest.php deleted file mode 100644 index 57d3532a..00000000 --- a/tests/phpunit/includes/SiteConfigurationTest.php +++ /dev/null @@ -1,311 +0,0 @@ -suffixes as $suffix ) { - if ( substr( $wiki, -strlen( $suffix ) ) == $suffix ) { - $site = $suffix; - $lang = substr( $wiki, 0, -strlen( $suffix ) ); - break; - } - } - return array( - 'suffix' => $site, - 'lang' => $lang, - 'params' => array( - 'lang' => $lang, - 'site' => $site, - 'wiki' => $wiki, - ), - 'tags' => array( 'tag' ), - ); -} - -class SiteConfigurationTest extends MediaWikiTestCase { - var $mConf; - - function setUp() { - $this->mConf = new SiteConfiguration; - - $this->mConf->suffixes = array( 'wiki' ); - $this->mConf->wikis = array( 'enwiki', 'dewiki', 'frwiki' ); - $this->mConf->settings = array( - 'simple' => array( - 'wiki' => 'wiki', - 'tag' => 'tag', - 'enwiki' => 'enwiki', - 'dewiki' => 'dewiki', - 'frwiki' => 'frwiki', - ), - - 'fallback' => array( - 'default' => 'default', - 'wiki' => 'wiki', - 'tag' => 'tag', - ), - - 'params' => array( - 'default' => '$lang $site $wiki', - ), - - '+global' => array( - 'wiki' => array( - 'wiki' => 'wiki', - ), - 'tag' => array( - 'tag' => 'tag', - ), - 'enwiki' => array( - 'enwiki' => 'enwiki', - ), - 'dewiki' => array( - 'dewiki' => 'dewiki', - ), - 'frwiki' => array( - 'frwiki' => 'frwiki', - ), - ), - - 'merge' => array( - '+wiki' => array( - 'wiki' => 'wiki', - ), - '+tag' => array( - 'tag' => 'tag', - ), - 'default' => array( - 'default' => 'default', - ), - '+enwiki' => array( - 'enwiki' => 'enwiki', - ), - '+dewiki' => array( - 'dewiki' => 'dewiki', - ), - '+frwiki' => array( - 'frwiki' => 'frwiki', - ), - ), - ); - - $GLOBALS['global'] = array( 'global' => 'global' ); - } - - - function testSiteFromDb() { - $this->assertEquals( - array( 'wikipedia', 'en' ), - $this->mConf->siteFromDB( 'enwiki' ), - 'siteFromDB()' - ); - $this->assertEquals( - array( 'wikipedia', '' ), - $this->mConf->siteFromDB( 'wiki' ), - 'siteFromDB() on a suffix' - ); - $this->assertEquals( - array( null, null ), - $this->mConf->siteFromDB( 'wikien' ), - 'siteFromDB() on a non-existing wiki' - ); - - $this->mConf->suffixes = array( 'wiki', '' ); - $this->assertEquals( - array( '', 'wikien' ), - $this->mConf->siteFromDB( 'wikien' ), - 'siteFromDB() on a non-existing wiki (2)' - ); - } - - function testGetLocalDatabases() { - $this->assertEquals( - array( 'enwiki', 'dewiki', 'frwiki' ), - $this->mConf->getLocalDatabases(), - 'getLocalDatabases()' - ); - } - - function testGetConfVariables() { - $this->assertEquals( - 'enwiki', - $this->mConf->get( 'simple', 'enwiki', 'wiki' ), - 'get(): simple setting on an existing wiki' - ); - $this->assertEquals( - 'dewiki', - $this->mConf->get( 'simple', 'dewiki', 'wiki' ), - 'get(): simple setting on an existing wiki (2)' - ); - $this->assertEquals( - 'frwiki', - $this->mConf->get( 'simple', 'frwiki', 'wiki' ), - 'get(): simple setting on an existing wiki (3)' - ); - $this->assertEquals( - 'wiki', - $this->mConf->get( 'simple', 'wiki', 'wiki' ), - 'get(): simple setting on an suffix' - ); - $this->assertEquals( - 'wiki', - $this->mConf->get( 'simple', 'eswiki', 'wiki' ), - 'get(): simple setting on an non-existing wiki' - ); - - $this->assertEquals( - 'wiki', - $this->mConf->get( 'fallback', 'enwiki', 'wiki' ), - 'get(): fallback setting on an existing wiki' - ); - $this->assertEquals( - 'tag', - $this->mConf->get( 'fallback', 'dewiki', 'wiki', array(), array( 'tag' ) ), - 'get(): fallback setting on an existing wiki (with wiki tag)' - ); - $this->assertEquals( - 'wiki', - $this->mConf->get( 'fallback', 'wiki', 'wiki' ), - 'get(): fallback setting on an suffix' - ); - $this->assertEquals( - 'wiki', - $this->mConf->get( 'fallback', 'wiki', 'wiki', array(), array( 'tag' ) ), - 'get(): fallback setting on an suffix (with wiki tag)' - ); - $this->assertEquals( - 'wiki', - $this->mConf->get( 'fallback', 'eswiki', 'wiki' ), - 'get(): fallback setting on an non-existing wiki' - ); - $this->assertEquals( - 'tag', - $this->mConf->get( 'fallback', 'eswiki', 'wiki', array(), array( 'tag' ) ), - 'get(): fallback setting on an non-existing wiki (with wiki tag)' - ); - - $common = array( 'wiki' => 'wiki', 'default' => 'default' ); - $commonTag = array( 'tag' => 'tag', 'wiki' => 'wiki', 'default' => 'default' ); - $this->assertEquals( - array( 'enwiki' => 'enwiki' ) + $common, - $this->mConf->get( 'merge', 'enwiki', 'wiki' ), - 'get(): merging setting on an existing wiki' - ); - $this->assertEquals( - array( 'enwiki' => 'enwiki' ) + $commonTag, - $this->mConf->get( 'merge', 'enwiki', 'wiki', array(), array( 'tag' ) ), - 'get(): merging setting on an existing wiki (with tag)' - ); - $this->assertEquals( - array( 'dewiki' => 'dewiki' ) + $common, - $this->mConf->get( 'merge', 'dewiki', 'wiki' ), - 'get(): merging setting on an existing wiki (2)' - ); - $this->assertEquals( - array( 'dewiki' => 'dewiki' ) + $commonTag, - $this->mConf->get( 'merge', 'dewiki', 'wiki', array(), array( 'tag' ) ), - 'get(): merging setting on an existing wiki (2) (with tag)' - ); - $this->assertEquals( - array( 'frwiki' => 'frwiki' ) + $common, - $this->mConf->get( 'merge', 'frwiki', 'wiki' ), - 'get(): merging setting on an existing wiki (3)' - ); - $this->assertEquals( - array( 'frwiki' => 'frwiki' ) + $commonTag, - $this->mConf->get( 'merge', 'frwiki', 'wiki', array(), array( 'tag' ) ), - 'get(): merging setting on an existing wiki (3) (with tag)' - ); - $this->assertEquals( - array( 'wiki' => 'wiki' ) + $common, - $this->mConf->get( 'merge', 'wiki', 'wiki' ), - 'get(): merging setting on an suffix' - ); - $this->assertEquals( - array( 'wiki' => 'wiki' ) + $commonTag, - $this->mConf->get( 'merge', 'wiki', 'wiki', array(), array( 'tag' ) ), - 'get(): merging setting on an suffix (with tag)' - ); - $this->assertEquals( - $common, - $this->mConf->get( 'merge', 'eswiki', 'wiki' ), - 'get(): merging setting on an non-existing wiki' - ); - $this->assertEquals( - $commonTag, - $this->mConf->get( 'merge', 'eswiki', 'wiki', array(), array( 'tag' ) ), - 'get(): merging setting on an non-existing wiki (with tag)' - ); - } - - function testSiteFromDbWithCallback() { - $this->mConf->siteParamsCallback = 'getSiteParams'; - - $this->assertEquals( - array( 'wiki', 'en' ), - $this->mConf->siteFromDB( 'enwiki' ), - 'siteFromDB() with callback' - ); - $this->assertEquals( - array( 'wiki', '' ), - $this->mConf->siteFromDB( 'wiki' ), - 'siteFromDB() with callback on a suffix' - ); - $this->assertEquals( - array( null, null ), - $this->mConf->siteFromDB( 'wikien' ), - 'siteFromDB() with callback on a non-existing wiki' - ); - } - - function testParameterReplacement() { - $this->mConf->siteParamsCallback = 'getSiteParams'; - - $this->assertEquals( - 'en wiki enwiki', - $this->mConf->get( 'params', 'enwiki', 'wiki' ), - 'get(): parameter replacement on an existing wiki' - ); - $this->assertEquals( - 'de wiki dewiki', - $this->mConf->get( 'params', 'dewiki', 'wiki' ), - 'get(): parameter replacement on an existing wiki (2)' - ); - $this->assertEquals( - 'fr wiki frwiki', - $this->mConf->get( 'params', 'frwiki', 'wiki' ), - 'get(): parameter replacement on an existing wiki (3)' - ); - $this->assertEquals( - ' wiki wiki', - $this->mConf->get( 'params', 'wiki', 'wiki' ), - 'get(): parameter replacement on an suffix' - ); - $this->assertEquals( - 'es wiki eswiki', - $this->mConf->get( 'params', 'eswiki', 'wiki' ), - 'get(): parameter replacement on an non-existing wiki' - ); - } - - function testGetAllGlobals() { - $this->mConf->siteParamsCallback = 'getSiteParams'; - - $getall = array( - 'simple' => 'enwiki', - 'fallback' => 'tag', - 'params' => 'en wiki enwiki', - 'global' => array( 'enwiki' => 'enwiki' ) + $GLOBALS['global'], - 'merge' => array( 'enwiki' => 'enwiki', 'tag' => 'tag', 'wiki' => 'wiki', 'default' => 'default' ), - ); - $this->assertEquals( $getall, $this->mConf->getAll( 'enwiki' ), 'getAll()' ); - - $this->mConf->extractAllGlobals( 'enwiki', 'wiki' ); - - $this->assertEquals( $getall['simple'], $GLOBALS['simple'], 'extractAllGlobals(): simple setting' ); - $this->assertEquals( $getall['fallback'], $GLOBALS['fallback'], 'extractAllGlobals(): fallback setting' ); - $this->assertEquals( $getall['params'], $GLOBALS['params'], 'extractAllGlobals(): parameter replacement' ); - $this->assertEquals( $getall['global'], $GLOBALS['global'], 'extractAllGlobals(): merging with global' ); - $this->assertEquals( $getall['merge'], $GLOBALS['merge'], 'extractAllGlobals(): merging setting' ); - } -} diff --git a/tests/phpunit/includes/TemplateCategoriesTest.php b/tests/phpunit/includes/TemplateCategoriesTest.php deleted file mode 100644 index 39ce6e31..00000000 --- a/tests/phpunit/includes/TemplateCategoriesTest.php +++ /dev/null @@ -1,36 +0,0 @@ -mRights = array( 'createpage', 'edit', 'purge' ); - - $status = $page->doEdit( '{{Categorising template}}', 'Create a page with a template', 0, false, $user ); - $this->assertEquals( - array() - , $title->getParentCategories() - ); - - $template = WikiPage::factory( Title::newFromText( 'Template:Categorising template' ) ); - $status = $template->doEdit( '[[Category:Solved bugs]]', 'Add a category through a template', 0, false, $user ); - - // Run the job queue - $jobs = new RunJobs; - $jobs->loadParamsAndArgs( null, array( 'quiet' => true ), null ); - $jobs->execute(); - - $this->assertEquals( - array( 'Category:Solved_bugs' => $title->getPrefixedText() ) - , $title->getParentCategories() - ); - } - -} diff --git a/tests/phpunit/includes/TestUser.php b/tests/phpunit/includes/TestUser.php deleted file mode 100644 index c4d89455..00000000 --- a/tests/phpunit/includes/TestUser.php +++ /dev/null @@ -1,58 +0,0 @@ -username = $username; - $this->realname = $realname; - $this->email = $email; - $this->groups = $groups; - - // don't allow user to hardcode or select passwords -- people sometimes run tests - // on live wikis. Sometimes we create sysop users in these tests. A sysop user with - // a known password would be a Bad Thing. - $this->password = User::randomPassword(); - - $this->user = User::newFromName( $this->username ); - $this->user->load(); - - // In an ideal world we'd have a new wiki (or mock data store) for every single test. - // But for now, we just need to create or update the user with the desired properties. - // we particularly need the new password, since we just generated it randomly. - // In core MediaWiki, there is no functionality to delete users, so this is the best we can do. - if ( !$this->user->getID() ) { - // create the user - $this->user = User::createNew( - $this->username, array( - "email" => $this->email, - "real_name" => $this->realname - ) - ); - if ( !$this->user ) { - throw new Exception( "error creating user" ); - } - } - - // update the user to use the new random password and other details - $this->user->setPassword( $this->password ); - $this->user->setEmail( $this->email ); - $this->user->setRealName( $this->realname ); - // remove all groups, replace with any groups specified - foreach ( $this->user->getGroups() as $group ) { - $this->user->removeGroup( $group ); - } - if ( count( $this->groups ) ) { - foreach ( $this->groups as $group ) { - $this->user->addGroup( $group ); - } - } - $this->user->saveSettings(); - - } -} diff --git a/tests/phpunit/includes/TimeAdjustTest.php b/tests/phpunit/includes/TimeAdjustTest.php deleted file mode 100644 index cd027c5b..00000000 --- a/tests/phpunit/includes/TimeAdjustTest.php +++ /dev/null @@ -1,51 +0,0 @@ -iniSet( 'precision', 15 ); - } - - public function tearDown() { - global $wgLocalTZoffset; - $wgLocalTZoffset = self::$offset; - parent::tearDown(); - } - - # Test offset usage for a given language::userAdjust - function testUserAdjust() { - global $wgLocalTZoffset, $wgContLang; - - $wgContLang = $en = Language::factory( 'en' ); - - #  Collection of parameters for Language_t_Offset. - # Format: date to be formatted, localTZoffset value, expected date - $userAdjust_tests = array( - array( 20061231235959, 0, 20061231235959 ), - array( 20061231235959, 5, 20070101000459 ), - array( 20061231235959, 15, 20070101001459 ), - array( 20061231235959, 60, 20070101005959 ), - array( 20061231235959, 90, 20070101012959 ), - array( 20061231235959, 120, 20070101015959 ), - array( 20061231235959, 540, 20070101085959 ), - array( 20061231235959, -5, 20061231235459 ), - array( 20061231235959, -30, 20061231232959 ), - array( 20061231235959, -60, 20061231225959 ), - ); - - foreach ( $userAdjust_tests as $data ) { - $wgLocalTZoffset = $data[1]; - - $this->assertEquals( - strval( $data[2] ), - strval( $en->userAdjust( $data[0], '' ) ), - "User adjust {$data[0]} by {$data[1]} minutes should give {$data[2]}" - ); - } - } -} diff --git a/tests/phpunit/includes/TimestampTest.php b/tests/phpunit/includes/TimestampTest.php deleted file mode 100644 index 231228f5..00000000 --- a/tests/phpunit/includes/TimestampTest.php +++ /dev/null @@ -1,72 +0,0 @@ -assertEquals( $expected, $timestamp->getTimestamp( TS_MW ) ); - } - - /** - * Test outputting valid timestamps to different formats. - * @dataProvider provideValidTimestamps - */ - function testValidOutput( $format, $expected, $original ) { - $timestamp = new MWTimestamp( $original ); - $this->assertEquals( $expected, (string) $timestamp->getTimestamp( $format ) ); - } - - /** - * Test an invalid timestamp. - * @expectedException TimestampException - */ - function testInvalidParse() { - $timestamp = new MWTimestamp( "This is not a timestamp." ); - } - - /** - * Test requesting an invalid output format. - * @expectedException TimestampException - */ - function testInvalidOutput() { - $timestamp = new MWTimestamp( '1343761268' ); - $timestamp->getTimestamp( 98 ); - } - - /** - * Test human readable timestamp format. - */ - function testHumanOutput() { - $timestamp = new MWTimestamp( time() - 3600 ); - $this->assertEquals( "1 hour ago", $timestamp->getHumanTimestamp()->toString() ); - } - - /** - * Returns a list of valid timestamps in the format: - * array( type, timestamp_of_type, timestamp_in_MW ) - */ - function provideValidTimestamps() { - return array( - // Various formats - array( TS_UNIX, '1343761268', '20120731190108' ), - array( TS_MW, '20120731190108', '20120731190108' ), - array( TS_DB, '2012-07-31 19:01:08', '20120731190108' ), - array( TS_ISO_8601, '2012-07-31T19:01:08Z', '20120731190108' ), - array( TS_ISO_8601_BASIC, '20120731T190108Z', '20120731190108' ), - array( TS_EXIF, '2012:07:31 19:01:08', '20120731190108' ), - array( TS_RFC2822, 'Tue, 31 Jul 2012 19:01:08 GMT', '20120731190108' ), - array( TS_ORACLE, '31-07-2012 19:01:08.000000', '20120731190108' ), - array( TS_POSTGRES, '2012-07-31 19:01:08 GMT', '20120731190108' ), - array( TS_DB2, '2012-07-31 19:01:08', '20120731190108' ), - // Some extremes and weird values - array( TS_ISO_8601, '9999-12-31T23:59:59Z', '99991231235959' ), - array( TS_UNIX, '-62135596801', '00001231235959' ) - ); - } -} diff --git a/tests/phpunit/includes/TitleMethodsTest.php b/tests/phpunit/includes/TitleMethodsTest.php deleted file mode 100644 index aed658ba..00000000 --- a/tests/phpunit/includes/TitleMethodsTest.php +++ /dev/null @@ -1,201 +0,0 @@ -assertEquals( $expectedBool, $titleA->equals( $titleB ) ); - $this->assertEquals( $expectedBool, $titleB->equals( $titleA ) ); - } - - public function dataInNamespace() { - return array( - array( 'Main Page', NS_MAIN, true ), - array( 'Main Page', NS_TALK, false ), - array( 'Main Page', NS_USER, false ), - array( 'User:Foo', NS_USER, true ), - array( 'User:Foo', NS_USER_TALK, false ), - array( 'User:Foo', NS_TEMPLATE, false ), - array( 'User_talk:Foo', NS_USER_TALK, true ), - array( 'User_talk:Foo', NS_USER, false ), - ); - } - - /** - * @dataProvider dataInNamespace - */ - public function testInNamespace( $title, $ns, $expectedBool ) { - $title = Title::newFromText( $title ); - $this->assertEquals( $expectedBool, $title->inNamespace( $ns ) ); - } - - public function testInNamespaces() { - $mainpage = Title::newFromText( 'Main Page' ); - $this->assertTrue( $mainpage->inNamespaces( NS_MAIN, NS_USER ) ); - $this->assertTrue( $mainpage->inNamespaces( array( NS_MAIN, NS_USER ) ) ); - $this->assertTrue( $mainpage->inNamespaces( array( NS_USER, NS_MAIN ) ) ); - $this->assertFalse( $mainpage->inNamespaces( array( NS_PROJECT, NS_TEMPLATE ) ) ); - } - - public function dataHasSubjectNamespace() { - return array( - array( 'Main Page', NS_MAIN, true ), - array( 'Main Page', NS_TALK, true ), - array( 'Main Page', NS_USER, false ), - array( 'User:Foo', NS_USER, true ), - array( 'User:Foo', NS_USER_TALK, true ), - array( 'User:Foo', NS_TEMPLATE, false ), - array( 'User_talk:Foo', NS_USER_TALK, true ), - array( 'User_talk:Foo', NS_USER, true ), - ); - } - - /** - * @dataProvider dataHasSubjectNamespace - */ - public function testHasSubjectNamespace( $title, $ns, $expectedBool ) { - $title = Title::newFromText( $title ); - $this->assertEquals( $expectedBool, $title->hasSubjectNamespace( $ns ) ); - } - - public function dataIsCssOrJsPage() { - return array( - array( 'Foo', false ), - array( 'Foo.js', false ), - array( 'Foo/bar.js', false ), - array( 'User:Foo', false ), - array( 'User:Foo.js', false ), - array( 'User:Foo/bar.js', false ), - array( 'User:Foo/bar.css', false ), - array( 'User talk:Foo/bar.css', false ), - array( 'User:Foo/bar.js.xxx', false ), - array( 'User:Foo/bar.xxx', false ), - array( 'MediaWiki:Foo.js', true ), - array( 'MediaWiki:Foo.css', true ), - array( 'MediaWiki:Foo.JS', false ), - array( 'MediaWiki:Foo.CSS', false ), - array( 'MediaWiki:Foo.css.xxx', false ), - ); - } - - /** - * @dataProvider dataIsCssOrJsPage - */ - public function testIsCssOrJsPage( $title, $expectedBool ) { - $title = Title::newFromText( $title ); - $this->assertEquals( $expectedBool, $title->isCssOrJsPage() ); - } - - - public function dataIsCssJsSubpage() { - return array( - array( 'Foo', false ), - array( 'Foo.js', false ), - array( 'Foo/bar.js', false ), - array( 'User:Foo', false ), - array( 'User:Foo.js', false ), - array( 'User:Foo/bar.js', true ), - array( 'User:Foo/bar.css', true ), - array( 'User talk:Foo/bar.css', false ), - array( 'User:Foo/bar.js.xxx', false ), - array( 'User:Foo/bar.xxx', false ), - array( 'MediaWiki:Foo.js', false ), - array( 'User:Foo/bar.JS', false ), - array( 'User:Foo/bar.CSS', false ), - ); - } - - /** - * @dataProvider dataIsCssJsSubpage - */ - public function testIsCssJsSubpage( $title, $expectedBool ) { - $title = Title::newFromText( $title ); - $this->assertEquals( $expectedBool, $title->isCssJsSubpage() ); - } - - public function dataIsCssSubpage() { - return array( - array( 'Foo', false ), - array( 'Foo.css', false ), - array( 'User:Foo', false ), - array( 'User:Foo.js', false ), - array( 'User:Foo.css', false ), - array( 'User:Foo/bar.js', false ), - array( 'User:Foo/bar.css', true ), - ); - } - - /** - * @dataProvider dataIsCssSubpage - */ - public function testIsCssSubpage( $title, $expectedBool ) { - $title = Title::newFromText( $title ); - $this->assertEquals( $expectedBool, $title->isCssSubpage() ); - } - - public function dataIsJsSubpage() { - return array( - array( 'Foo', false ), - array( 'Foo.css', false ), - array( 'User:Foo', false ), - array( 'User:Foo.js', false ), - array( 'User:Foo.css', false ), - array( 'User:Foo/bar.js', true ), - array( 'User:Foo/bar.css', false ), - ); - } - - /** - * @dataProvider dataIsJsSubpage - */ - public function testIsJsSubpage( $title, $expectedBool ) { - $title = Title::newFromText( $title ); - $this->assertEquals( $expectedBool, $title->isJsSubpage() ); - } - - public function dataIsWikitextPage() { - return array( - array( 'Foo', true ), - array( 'Foo.js', true ), - array( 'Foo/bar.js', true ), - array( 'User:Foo', true ), - array( 'User:Foo.js', true ), - array( 'User:Foo/bar.js', false ), - array( 'User:Foo/bar.css', false ), - array( 'User talk:Foo/bar.css', true ), - array( 'User:Foo/bar.js.xxx', true ), - array( 'User:Foo/bar.xxx', true ), - array( 'MediaWiki:Foo.js', false ), - array( 'MediaWiki:Foo.css', false ), - array( 'MediaWiki:Foo/bar.css', false ), - array( 'User:Foo/bar.JS', true ), - array( 'User:Foo/bar.CSS', true ), - ); - } - - /** - * @dataProvider dataIsWikitextPage - */ - public function testIsWikitextPage( $title, $expectedBool ) { - $title = Title::newFromText( $title ); - $this->assertEquals( $expectedBool, $title->isWikitextPage() ); - } - -} diff --git a/tests/phpunit/includes/TitlePermissionTest.php b/tests/phpunit/includes/TitlePermissionTest.php deleted file mode 100644 index f62ac5dd..00000000 --- a/tests/phpunit/includes/TitlePermissionTest.php +++ /dev/null @@ -1,660 +0,0 @@ -userName = "Useruser"; - $this->altUserName = "Altuseruser"; - date_default_timezone_set( $wgLocaltimezone ); - $wgLocalTZoffset = date( "Z" ) / 60; - - $this->title = Title::makeTitle( NS_MAIN, "Main Page" ); - if ( !isset( $this->userUser ) || !( $this->userUser instanceOf User ) ) { - $this->userUser = User::newFromName( $this->userName ); - - if ( !$this->userUser->getID() ) { - $this->userUser = User::createNew( $this->userName, array( - "email" => "test@example.com", - "real_name" => "Test User" ) ); - $this->userUser->load(); - } - - $this->altUser = User::newFromName( $this->altUserName ); - if ( !$this->altUser->getID() ) { - $this->altUser = User::createNew( $this->altUserName, array( - "email" => "alttest@example.com", - "real_name" => "Test User Alt" ) ); - $this->altUser->load(); - } - - $this->anonUser = User::newFromId( 0 ); - - $this->user = $this->userUser; - } - } - - function tearDown() { - parent::tearDown(); - } - - function setUserPerm( $perm ) { - // Setting member variables is evil!!! - - if ( is_array( $perm ) ) { - $this->user->mRights = $perm; - } else { - $this->user->mRights = array( $perm ); - } - } - - function setTitle( $ns, $title = "Main_Page" ) { - $this->title = Title::makeTitle( $ns, $title ); - } - - function setUser( $userName = null ) { - if ( $userName === 'anon' ) { - $this->user = $this->anonUser; - } elseif ( $userName === null || $userName === $this->userName ) { - $this->user = $this->userUser; - } else { - $this->user = $this->altUser; - } - - global $wgUser; - $wgUser = $this->user; - } - - function testQuickPermissions() { - global $wgContLang; - $prefix = $wgContLang->getFormattedNsText( NS_PROJECT ); - - $this->setUser( 'anon' ); - $this->setTitle( NS_TALK ); - $this->setUserPerm( "createtalk" ); - $res = $this->title->getUserPermissionsErrors( 'create', $this->user ); - $this->assertEquals( array(), $res ); - - $this->setTitle( NS_TALK ); - $this->setUserPerm( "createpage" ); - $res = $this->title->getUserPermissionsErrors( 'create', $this->user ); - $this->assertEquals( array( array( "nocreatetext" ) ), $res ); - - $this->setTitle( NS_TALK ); - $this->setUserPerm( "" ); - $res = $this->title->getUserPermissionsErrors( 'create', $this->user ); - $this->assertEquals( array( array( 'nocreatetext' ) ), $res ); - - $this->setTitle( NS_MAIN ); - $this->setUserPerm( "createpage" ); - $res = $this->title->getUserPermissionsErrors( 'create', $this->user ); - $this->assertEquals( array( ), $res ); - - $this->setTitle( NS_MAIN ); - $this->setUserPerm( "createtalk" ); - $res = $this->title->getUserPermissionsErrors( 'create', $this->user ); - $this->assertEquals( array( array( 'nocreatetext' ) ), $res ); - - $this->setUser( $this->userName ); - $this->setTitle( NS_TALK ); - $this->setUserPerm( "createtalk" ); - $res = $this->title->getUserPermissionsErrors( 'create', $this->user ); - $this->assertEquals( array( ), $res ); - - $this->setTitle( NS_TALK ); - $this->setUserPerm( "createpage" ); - $res = $this->title->getUserPermissionsErrors( 'create', $this->user ); - $this->assertEquals( array( array( 'nocreate-loggedin' ) ), $res ); - - $this->setTitle( NS_TALK ); - $this->setUserPerm( "" ); - $res = $this->title->getUserPermissionsErrors( 'create', $this->user ); - $this->assertEquals( array( array( 'nocreate-loggedin' ) ), $res ); - - $this->setTitle( NS_MAIN ); - $this->setUserPerm( "createpage" ); - $res = $this->title->getUserPermissionsErrors( 'create', $this->user ); - $this->assertEquals( array( ), $res ); - - $this->setTitle( NS_MAIN ); - $this->setUserPerm( "createtalk" ); - $res = $this->title->getUserPermissionsErrors( 'create', $this->user ); - $this->assertEquals( array( array( 'nocreate-loggedin' ) ), $res ); - - $this->setTitle( NS_MAIN ); - $this->setUserPerm( "" ); - $res = $this->title->getUserPermissionsErrors( 'create', $this->user ); - $this->assertEquals( array( array( 'nocreate-loggedin' ) ), $res ); - - $this->setUser( 'anon' ); - $this->setTitle( NS_USER, $this->userName . '' ); - $this->setUserPerm( "" ); - $res = $this->title->getUserPermissionsErrors( 'move', $this->user ); - $this->assertEquals( array( array( 'cant-move-user-page' ), array( 'movenologintext' ) ), $res ); - - $this->setTitle( NS_USER, $this->userName . '/subpage' ); - $this->setUserPerm( "" ); - $res = $this->title->getUserPermissionsErrors( 'move', $this->user ); - $this->assertEquals( array( array( 'movenologintext' ) ), $res ); - - $this->setTitle( NS_USER, $this->userName . '' ); - $this->setUserPerm( "move-rootuserpages" ); - $res = $this->title->getUserPermissionsErrors( 'move', $this->user ); - $this->assertEquals( array( array( 'movenologintext' ) ), $res ); - - $this->setTitle( NS_USER, $this->userName . '/subpage' ); - $this->setUserPerm( "move-rootuserpages" ); - $res = $this->title->getUserPermissionsErrors( 'move', $this->user ); - $this->assertEquals( array( array( 'movenologintext' ) ), $res ); - - $this->setTitle( NS_USER, $this->userName . '' ); - $this->setUserPerm( "" ); - $res = $this->title->getUserPermissionsErrors( 'move', $this->user ); - $this->assertEquals( array( array( 'cant-move-user-page' ), array( 'movenologintext' ) ), $res ); - - $this->setTitle( NS_USER, $this->userName . '/subpage' ); - $this->setUserPerm( "" ); - $res = $this->title->getUserPermissionsErrors( 'move', $this->user ); - $this->assertEquals( array( array( 'movenologintext' ) ), $res ); - - $this->setTitle( NS_USER, $this->userName . '' ); - $this->setUserPerm( "move-rootuserpages" ); - $res = $this->title->getUserPermissionsErrors( 'move', $this->user ); - $this->assertEquals( array( array( 'movenologintext' ) ), $res ); - - $this->setTitle( NS_USER, $this->userName . '/subpage' ); - $this->setUserPerm( "move-rootuserpages" ); - $res = $this->title->getUserPermissionsErrors( 'move', $this->user ); - $this->assertEquals( array( array( 'movenologintext' ) ), $res ); - - $this->setUser( $this->userName ); - $this->setTitle( NS_FILE, "img.png" ); - $this->setUserPerm( "" ); - $res = $this->title->getUserPermissionsErrors( 'move', $this->user ); - $this->assertEquals( array( array( 'movenotallowedfile' ), array( 'movenotallowed' ) ), $res ); - - $this->setTitle( NS_FILE, "img.png" ); - $this->setUserPerm( "movefile" ); - $res = $this->title->getUserPermissionsErrors( 'move', $this->user ); - $this->assertEquals( array( array( 'movenotallowed' ) ), $res ); - - $this->setUser( 'anon' ); - $this->setTitle( NS_FILE, "img.png" ); - $this->setUserPerm( "" ); - $res = $this->title->getUserPermissionsErrors( 'move', $this->user ); - $this->assertEquals( array( array( 'movenotallowedfile' ), array( 'movenologintext' ) ), $res ); - - $this->setTitle( NS_FILE, "img.png" ); - $this->setUserPerm( "movefile" ); - $res = $this->title->getUserPermissionsErrors( 'move', $this->user ); - $this->assertEquals( array( array( 'movenologintext' ) ), $res ); - - $this->setUser( $this->userName ); - $this->setUserPerm( "move" ); - $this->runGroupPermissions( 'move', array( array( 'movenotallowedfile' ) ) ); - - $this->setUserPerm( "" ); - $this->runGroupPermissions( 'move', array( array( 'movenotallowedfile' ), array( 'movenotallowed' ) ) ); - - $this->setUser( 'anon' ); - $this->setUserPerm( "move" ); - $this->runGroupPermissions( 'move', array( array( 'movenotallowedfile' ) ) ); - - $this->setUserPerm( "" ); - $this->runGroupPermissions( 'move', array( array( 'movenotallowedfile' ), array( 'movenotallowed' ) ), - array( array( 'movenotallowedfile' ), array( 'movenologintext' ) ) ); - - $this->setTitle( NS_MAIN ); - $this->setUser( 'anon' ); - $this->setUserPerm( "move" ); - $this->runGroupPermissions( 'move', array( ) ); - - $this->setUserPerm( "" ); - $this->runGroupPermissions( 'move', array( array( 'movenotallowed' ) ), - array( array( 'movenologintext' ) ) ); - - $this->setUser( $this->userName ); - $this->setUserPerm( "" ); - $this->runGroupPermissions( 'move', array( array( 'movenotallowed' ) ) ); - - $this->setUserPerm( "move" ); - $this->runGroupPermissions( 'move', array( ) ); - - $this->setUser( 'anon' ); - $this->setUserPerm( 'move' ); - $res = $this->title->getUserPermissionsErrors( 'move-target', $this->user ); - $this->assertEquals( array( ), $res ); - - $this->setUserPerm( '' ); - $res = $this->title->getUserPermissionsErrors( 'move-target', $this->user ); - $this->assertEquals( array( array( 'movenotallowed' ) ), $res ); - - $this->setTitle( NS_USER ); - $this->setUser( $this->userName ); - $this->setUserPerm( array( "move", "move-rootuserpages" ) ); - $res = $this->title->getUserPermissionsErrors( 'move-target', $this->user ); - $this->assertEquals( array( ), $res ); - - $this->setUserPerm( "move" ); - $res = $this->title->getUserPermissionsErrors( 'move-target', $this->user ); - $this->assertEquals( array( array( 'cant-move-to-user-page' ) ), $res ); - - $this->setUser( 'anon' ); - $this->setUserPerm( array( "move", "move-rootuserpages" ) ); - $res = $this->title->getUserPermissionsErrors( 'move-target', $this->user ); - $this->assertEquals( array( ), $res ); - - $this->setTitle( NS_USER, "User/subpage" ); - $this->setUserPerm( array( "move", "move-rootuserpages" ) ); - $res = $this->title->getUserPermissionsErrors( 'move-target', $this->user ); - $this->assertEquals( array( ), $res ); - - $this->setUserPerm( "move" ); - $res = $this->title->getUserPermissionsErrors( 'move-target', $this->user ); - $this->assertEquals( array( ), $res ); - - $this->setUser( 'anon' ); - $check = array( 'edit' => array( array( array( 'badaccess-groups', "*, [[$prefix:Users|Users]]", 2 ) ), - array( array( 'badaccess-group0' ) ), - array( ), true ), - 'protect' => array( array( array( 'badaccess-groups', "[[$prefix:Administrators|Administrators]]", 1 ), array( 'protect-cantedit' ) ), - array( array( 'badaccess-group0' ), array( 'protect-cantedit' ) ), - array( array( 'protect-cantedit' ) ), false ), - '' => array( array( ), array( ), array( ), true ) ); - global $wgUser; - $wgUser = $this->user; - foreach ( array( "edit", "protect", "" ) as $action ) { - $this->setUserPerm( null ); - $this->assertEquals( $check[$action][0], - $this->title->getUserPermissionsErrors( $action, $this->user, true ) ); - - global $wgGroupPermissions; - $old = $wgGroupPermissions; - $wgGroupPermissions = array(); - - $this->assertEquals( $check[$action][1], - $this->title->getUserPermissionsErrors( $action, $this->user, true ) ); - $wgGroupPermissions = $old; - - $this->setUserPerm( $action ); - $this->assertEquals( $check[$action][2], - $this->title->getUserPermissionsErrors( $action, $this->user, true ) ); - - $this->setUserPerm( $action ); - $this->assertEquals( $check[$action][3], - $this->title->userCan( $action, true ) ); - $this->assertEquals( $check[$action][3], - $this->title->quickUserCan( $action ) ); - - # count( User::getGroupsWithPermissions( $action ) ) < 1 - } - } - - function runGroupPermissions( $action, $result, $result2 = null ) { - global $wgGroupPermissions; - - if ( $result2 === null ) $result2 = $result; - - $wgGroupPermissions['autoconfirmed']['move'] = false; - $wgGroupPermissions['user']['move'] = false; - $res = $this->title->getUserPermissionsErrors( $action, $this->user ); - $this->assertEquals( $result, $res ); - - $wgGroupPermissions['autoconfirmed']['move'] = true; - $wgGroupPermissions['user']['move'] = false; - $res = $this->title->getUserPermissionsErrors( $action, $this->user ); - $this->assertEquals( $result2, $res ); - - $wgGroupPermissions['autoconfirmed']['move'] = true; - $wgGroupPermissions['user']['move'] = true; - $res = $this->title->getUserPermissionsErrors( $action, $this->user ); - $this->assertEquals( $result2, $res ); - - $wgGroupPermissions['autoconfirmed']['move'] = false; - $wgGroupPermissions['user']['move'] = true; - $res = $this->title->getUserPermissionsErrors( $action, $this->user ); - $this->assertEquals( $result2, $res ); - } - - function testSpecialsAndNSPermissions() { - $this->setUser( $this->userName ); - global $wgUser; - $wgUser = $this->user; - - $this->setTitle( NS_SPECIAL ); - - $this->assertEquals( array( array( 'badaccess-group0' ), array( 'ns-specialprotected' ) ), - $this->title->getUserPermissionsErrors( 'bogus', $this->user ) ); - $this->assertEquals( array( array( 'badaccess-group0' ) ), - $this->title->getUserPermissionsErrors( 'execute', $this->user ) ); - - $this->setTitle( NS_MAIN ); - $this->setUserPerm( 'bogus' ); - $this->assertEquals( array( ), - $this->title->getUserPermissionsErrors( 'bogus', $this->user ) ); - - $this->setTitle( NS_MAIN ); - $this->setUserPerm( '' ); - $this->assertEquals( array( array( 'badaccess-group0' ) ), - $this->title->getUserPermissionsErrors( 'bogus', $this->user ) ); - - global $wgNamespaceProtection; - $wgNamespaceProtection[NS_USER] = array ( 'bogus' ); - $this->setTitle( NS_USER ); - $this->setUserPerm( '' ); - $this->assertEquals( array( array( 'badaccess-group0' ), array( 'namespaceprotected', 'User' ) ), - $this->title->getUserPermissionsErrors( 'bogus', $this->user ) ); - - $this->setTitle( NS_MEDIAWIKI ); - $this->setUserPerm( 'bogus' ); - $this->assertEquals( array( array( 'protectedinterface' ) ), - $this->title->getUserPermissionsErrors( 'bogus', $this->user ) ); - - $this->setTitle( NS_MEDIAWIKI ); - $this->setUserPerm( 'bogus' ); - $this->assertEquals( array( array( 'protectedinterface' ) ), - $this->title->getUserPermissionsErrors( 'bogus', $this->user ) ); - - $wgNamespaceProtection = null; - $this->setUserPerm( 'bogus' ); - $this->assertEquals( array( ), - $this->title->getUserPermissionsErrors( 'bogus', $this->user ) ); - $this->assertEquals( true, - $this->title->userCan( 'bogus' ) ); - - $this->setUserPerm( '' ); - $this->assertEquals( array( array( 'badaccess-group0' ) ), - $this->title->getUserPermissionsErrors( 'bogus', $this->user ) ); - $this->assertEquals( false, - $this->title->userCan( 'bogus' ) ); - } - - function testCssAndJavascriptPermissions() { - $this->setUser( $this->userName ); - global $wgUser; - $wgUser = $this->user; - - $this->setTitle( NS_USER, $this->altUserName . '/test.js' ); - $this->runCSSandJSPermissions( - array( array( 'badaccess-group0' ), array( 'customjsprotected' ) ), - array( array( 'badaccess-group0' ), array( 'customjsprotected' ) ), - array( array( 'badaccess-group0' ) ) ); - - $this->setTitle( NS_USER, $this->altUserName . '/test.css' ); - $this->runCSSandJSPermissions( - array( array( 'badaccess-group0' ), array( 'customcssprotected' ) ), - array( array( 'badaccess-group0' ) ), - array( array( 'badaccess-group0' ), array( 'customcssprotected' ) ) ); - - $this->setTitle( NS_USER, $this->altUserName . '/tempo' ); - $this->runCSSandJSPermissions( - array( array( 'badaccess-group0' ) ), - array( array( 'badaccess-group0' ) ), - array( array( 'badaccess-group0' ) ) ); - } - - function runCSSandJSPermissions( $result0, $result1, $result2 ) { - $this->setUserPerm( '' ); - $this->assertEquals( $result0, - $this->title->getUserPermissionsErrors( 'bogus', - $this->user ) ); - - $this->setUserPerm( 'editusercss' ); - $this->assertEquals( $result1, - $this->title->getUserPermissionsErrors( 'bogus', - $this->user ) ); - - $this->setUserPerm( 'edituserjs' ); - $this->assertEquals( $result2, - $this->title->getUserPermissionsErrors( 'bogus', - $this->user ) ); - - $this->setUserPerm( 'editusercssjs' ); - $this->assertEquals( array( array( 'badaccess-group0' ) ), - $this->title->getUserPermissionsErrors( 'bogus', - $this->user ) ); - - $this->setUserPerm( array( 'edituserjs', 'editusercss' ) ); - $this->assertEquals( array( array( 'badaccess-group0' ) ), - $this->title->getUserPermissionsErrors( 'bogus', - $this->user ) ); - } - - function testPageRestrictions() { - global $wgUser, $wgContLang; - - $prefix = $wgContLang->getFormattedNsText( NS_PROJECT ); - - $wgUser = $this->user; - $this->setTitle( NS_MAIN ); - $this->title->mRestrictionsLoaded = true; - $this->setUserPerm( "edit" ); - $this->title->mRestrictions = array( "bogus" => array( 'bogus', "sysop", "protect", "" ) ); - - $this->assertEquals( array( ), - $this->title->getUserPermissionsErrors( 'edit', - $this->user ) ); - - $this->assertEquals( true, - $this->title->quickUserCan( 'edit' ) ); - $this->title->mRestrictions = array( "edit" => array( 'bogus', "sysop", "protect", "" ), - "bogus" => array( 'bogus', "sysop", "protect", "" ) ); - - $this->assertEquals( array( array( 'badaccess-group0' ), - array( 'protectedpagetext', 'bogus' ), - array( 'protectedpagetext', 'protect' ), - array( 'protectedpagetext', 'protect' ) ), - $this->title->getUserPermissionsErrors( 'bogus', - $this->user ) ); - $this->assertEquals( array( array( 'protectedpagetext', 'bogus' ), - array( 'protectedpagetext', 'protect' ), - array( 'protectedpagetext', 'protect' ) ), - $this->title->getUserPermissionsErrors( 'edit', - $this->user ) ); - $this->setUserPerm( "" ); - $this->assertEquals( array( array( 'badaccess-group0' ), - array( 'protectedpagetext', 'bogus' ), - array( 'protectedpagetext', 'protect' ), - array( 'protectedpagetext', 'protect' ) ), - $this->title->getUserPermissionsErrors( 'bogus', - $this->user ) ); - $this->assertEquals( array( array( 'badaccess-groups', "*, [[$prefix:Users|Users]]", 2 ), - array( 'protectedpagetext', 'bogus' ), - array( 'protectedpagetext', 'protect' ), - array( 'protectedpagetext', 'protect' ) ), - $this->title->getUserPermissionsErrors( 'edit', - $this->user ) ); - $this->setUserPerm( array( "edit", "editprotected" ) ); - $this->assertEquals( array( array( 'badaccess-group0' ), - array( 'protectedpagetext', 'bogus' ), - array( 'protectedpagetext', 'protect' ), - array( 'protectedpagetext', 'protect' ) ), - $this->title->getUserPermissionsErrors( 'bogus', - $this->user ) ); - $this->assertEquals( array( ), - $this->title->getUserPermissionsErrors( 'edit', - $this->user ) ); - $this->title->mCascadeRestriction = true; - $this->assertEquals( false, - $this->title->quickUserCan( 'bogus' ) ); - $this->assertEquals( false, - $this->title->quickUserCan( 'edit' ) ); - $this->assertEquals( array( array( 'badaccess-group0' ), - array( 'protectedpagetext', 'bogus' ), - array( 'protectedpagetext', 'protect' ), - array( 'protectedpagetext', 'protect' ) ), - $this->title->getUserPermissionsErrors( 'bogus', - $this->user ) ); - $this->assertEquals( array( array( 'protectedpagetext', 'bogus' ), - array( 'protectedpagetext', 'protect' ), - array( 'protectedpagetext', 'protect' ) ), - $this->title->getUserPermissionsErrors( 'edit', - $this->user ) ); - } - - function testCascadingSourcesRestrictions() { - global $wgUser; - $wgUser = $this->user; - $this->setTitle( NS_MAIN, "test page" ); - $this->setUserPerm( array( "edit", "bogus" ) ); - - $this->title->mCascadeSources = array( Title::makeTitle( NS_MAIN, "Bogus" ), Title::makeTitle( NS_MAIN, "UnBogus" ) ); - $this->title->mCascadingRestrictions = array( "bogus" => array( 'bogus', "sysop", "protect", "" ) ); - - $this->assertEquals( false, - $this->title->userCan( 'bogus' ) ); - $this->assertEquals( array( array( "cascadeprotected", 2, "* [[:Bogus]]\n* [[:UnBogus]]\n" ), - array( "cascadeprotected", 2, "* [[:Bogus]]\n* [[:UnBogus]]\n" ) ), - $this->title->getUserPermissionsErrors( 'bogus', $this->user ) ); - - $this->assertEquals( true, - $this->title->userCan( 'edit' ) ); - $this->assertEquals( array( ), - $this->title->getUserPermissionsErrors( 'edit', $this->user ) ); - - } - - function testActionPermissions() { - global $wgUser; - $wgUser = $this->user; - - $this->setUserPerm( array( "createpage" ) ); - $this->setTitle( NS_MAIN, "test page" ); - $this->title->mTitleProtection['pt_create_perm'] = ''; - $this->title->mTitleProtection['pt_user'] = $this->user->getID(); - $this->title->mTitleProtection['pt_expiry'] = wfGetDB( DB_SLAVE )->getInfinity(); - $this->title->mTitleProtection['pt_reason'] = 'test'; - $this->title->mCascadeRestriction = false; - - $this->assertEquals( array( array( 'titleprotected', 'Useruser', 'test' ) ), - $this->title->getUserPermissionsErrors( 'create', $this->user ) ); - $this->assertEquals( false, - $this->title->userCan( 'create' ) ); - - $this->title->mTitleProtection['pt_create_perm'] = 'sysop'; - $this->setUserPerm( array( 'createpage', 'protect' ) ); - $this->assertEquals( array( ), - $this->title->getUserPermissionsErrors( 'create', $this->user ) ); - $this->assertEquals( true, - $this->title->userCan( 'create' ) ); - - - $this->setUserPerm( array( 'createpage' ) ); - $this->assertEquals( array( array( 'titleprotected', 'Useruser', 'test' ) ), - $this->title->getUserPermissionsErrors( 'create', $this->user ) ); - $this->assertEquals( false, - $this->title->userCan( 'create' ) ); - - $this->setTitle( NS_MEDIA, "test page" ); - $this->setUserPerm( array( "move" ) ); - $this->assertEquals( false, - $this->title->userCan( 'move' ) ); - $this->assertEquals( array( array( 'immobile-source-namespace', 'Media' ) ), - $this->title->getUserPermissionsErrors( 'move', $this->user ) ); - - $this->setTitle( NS_MAIN, "test page" ); - $this->assertEquals( array( ), - $this->title->getUserPermissionsErrors( 'move', $this->user ) ); - $this->assertEquals( true, - $this->title->userCan( 'move' ) ); - - $this->title->mInterwiki = "no"; - $this->assertEquals( array( array( 'immobile-source-page' ) ), - $this->title->getUserPermissionsErrors( 'move', $this->user ) ); - $this->assertEquals( false, - $this->title->userCan( 'move' ) ); - - $this->setTitle( NS_MEDIA, "test page" ); - $this->assertEquals( false, - $this->title->userCan( 'move-target' ) ); - $this->assertEquals( array( array( 'immobile-target-namespace', 'Media' ) ), - $this->title->getUserPermissionsErrors( 'move-target', $this->user ) ); - - $this->setTitle( NS_MAIN, "test page" ); - $this->assertEquals( array( ), - $this->title->getUserPermissionsErrors( 'move-target', $this->user ) ); - $this->assertEquals( true, - $this->title->userCan( 'move-target' ) ); - - $this->title->mInterwiki = "no"; - $this->assertEquals( array( array( 'immobile-target-page' ) ), - $this->title->getUserPermissionsErrors( 'move-target', $this->user ) ); - $this->assertEquals( false, - $this->title->userCan( 'move-target' ) ); - - } - - function testUserBlock() { - global $wgUser, $wgEmailConfirmToEdit, $wgEmailAuthentication; - $wgEmailConfirmToEdit = true; - $wgEmailAuthentication = true; - $wgUser = $this->user; - - $this->setUserPerm( array( "createpage", "move" ) ); - $this->setTitle( NS_MAIN, "test page" ); - - # $short - $this->assertEquals( array( array( 'confirmedittext' ) ), - $this->title->getUserPermissionsErrors( 'move-target', $this->user ) ); - $wgEmailConfirmToEdit = false; - $this->assertEquals( true, $this->title->userCan( 'move-target' ) ); - - # $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' - $this->assertEquals( array( ), - $this->title->getUserPermissionsErrors( 'move-target', - $this->user ) ); - - global $wgLang; - $prev = time(); - $now = time() + 120; - $this->user->mBlockedby = $this->user->getId(); - $this->user->mBlock = new Block( '127.0.8.1', 0, $this->user->getId(), - 'no reason given', $prev + 3600, 1, 0 ); - $this->user->mBlock->mTimestamp = 0; - $this->assertEquals( array( array( 'autoblockedtext', - '[[User:Useruser|Useruser]]', 'no reason given', '127.0.0.1', - 'Useruser', null, 'infinite', '127.0.8.1', - $wgLang->timeanddate( wfTimestamp( TS_MW, $prev ), true ) ) ), - $this->title->getUserPermissionsErrors( 'move-target', - $this->user ) ); - - $this->assertEquals( false, $this->title->userCan( 'move-target' ) ); - // quickUserCan should ignore user blocks - $this->assertEquals( true, $this->title->quickUserCan( 'move-target' ) ); - - global $wgLocalTZoffset; - $wgLocalTZoffset = -60; - $this->user->mBlockedby = $this->user->getName(); - $this->user->mBlock = new Block( '127.0.8.1', 0, 1, 'no reason given', $now, 0, 10 ); - $this->assertEquals( array( array( 'blockedtext', - '[[User:Useruser|Useruser]]', 'no reason given', '127.0.0.1', - 'Useruser', null, '23:00, 31 December 1969', '127.0.8.1', - $wgLang->timeanddate( wfTimestamp( TS_MW, $now ), true ) ) ), - $this->title->getUserPermissionsErrors( 'move-target', $this->user ) ); - - # $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) - # $user->blockedFor() == '' - # $user->mBlock->mExpiry == 'infinity' - } -} diff --git a/tests/phpunit/includes/TitleTest.php b/tests/phpunit/includes/TitleTest.php deleted file mode 100644 index f61652df..00000000 --- a/tests/phpunit/includes/TitleTest.php +++ /dev/null @@ -1,155 +0,0 @@ -|", $chr ) !== false || preg_match( "/[\\x00-\\x1f\\x7f]/", $chr ) ) { - $this->assertFalse( (bool)preg_match( "/[$titlechars]/", $chr ), "chr($num) = $chr is not a valid titlechar" ); - } else { - $this->assertTrue( (bool)preg_match( "/[$titlechars]/", $chr ), "chr($num) = $chr is a valid titlechar" ); - } - } - } - - /** - * @dataProvider dataBug31100 - */ - function testBug31100FixSpecialName( $text, $expectedParam ) { - $title = Title::newFromText( $text ); - $fixed = $title->fixSpecialName(); - $stuff = explode( '/', $fixed->getDbKey(), 2 ); - if ( count( $stuff ) == 2 ) { - $par = $stuff[1]; - } else { - $par = null; - } - $this->assertEquals( $expectedParam, $par, "Bug 31100 regression check: Title->fixSpecialName() should preserve parameter" ); - } - - function dataBug31100() { - return array( - array( 'Special:Version', null ), - array( 'Special:Version/', '' ), - array( 'Special:Version/param', 'param' ), - ); - } - - /** - * Auth-less test of Title::isValidMoveOperation - * - * @group Database - * @param string $source - * @param string $target - * @param array|string|true $expected Required error - * @dataProvider dataTestIsValidMoveOperation - */ - function testIsValidMoveOperation( $source, $target, $expected ) { - $title = Title::newFromText( $source ); - $nt = Title::newFromText( $target ); - $errors = $title->isValidMoveOperation( $nt, false ); - if ( $expected === true ) { - $this->assertTrue( $errors ); - } else { - $errors = $this->flattenErrorsArray( $errors ); - foreach ( (array)$expected as $error ) { - $this->assertContains( $error, $errors ); - } - } - } - - function flattenErrorsArray( $errors ) { - $result = array(); - foreach ( $errors as $error ) { - $result[] = $error[0]; - } - return $result; - } - - function dataTestIsValidMoveOperation() { - return array( - array( 'Test', 'Test', 'selfmove' ), - array( 'File:Test.jpg', 'Page', 'imagenocrossnamespace' ) - ); - } - - - /** - * @dataProvider provideCasesForGetpageviewlanguage - */ - function testGetpageviewlanguage( $expected, $titleText, $contLang, $lang, $variant, $msg='' ) { - // Save globals - global $wgContLang, $wgLang, $wgAllowUserJs, $wgLanguageCode, $wgDefaultLanguageVariant; - $save['wgContLang'] = $wgContLang; - $save['wgLang'] = $wgLang; - $save['wgAllowUserJs'] = $wgAllowUserJs; - $save['wgLanguageCode'] = $wgLanguageCode; - $save['wgDefaultLanguageVariant'] = $wgDefaultLanguageVariant; - - // Setup test environnement: - $wgContLang = Language::factory( $contLang ); - $wgLang = Language::factory( $lang ); - # To test out .js titles: - $wgAllowUserJs = true; - $wgLanguageCode = $contLang; - $wgDefaultLanguageVariant = $variant; - - $title = Title::newFromText( $titleText ); - $this->assertInstanceOf( 'Title', $title, - "Test must be passed a valid title text, you gave '$titleText'" - ); - $this->assertEquals( $expected, - $title->getPageViewLanguage()->getCode(), - $msg - ); - - // Restore globals - $wgContLang = $save['wgContLang']; - $wgLang = $save['wgLang']; - $wgAllowUserJs = $save['wgAllowUserJs']; - $wgLanguageCode = $save['wgLanguageCode']; - $wgDefaultLanguageVariant = $save['wgDefaultLanguageVariant']; - } - - function provideCasesForGetpageviewlanguage() { - # Format: - # - expected - # - Title name - # - wgContLang (expected in most case) - # - wgLang (on some specific pages) - # - wgDefaultLanguageVariant - # - Optional message - return array( - array( 'fr', 'Main_page', 'fr', 'fr', false ), - array( 'es', 'Main_page', 'es', 'zh-tw', false ), - array( 'zh', 'Main_page', 'zh', 'zh-tw', false ), - - array( 'es', 'Main_page', 'es', 'zh-tw', 'zh-cn' ), - array( 'es', 'MediaWiki:About', 'es', 'zh-tw', 'zh-cn' ), - array( 'es', 'MediaWiki:About/', 'es', 'zh-tw', 'zh-cn' ), - array( 'de', 'MediaWiki:About/de', 'es', 'zh-tw', 'zh-cn' ), - array( 'en', 'MediaWiki:Common.js', 'es', 'zh-tw', 'zh-cn' ), - array( 'en', 'MediaWiki:Common.css', 'es', 'zh-tw', 'zh-cn' ), - array( 'en', 'User:JohnDoe/Common.js', 'es', 'zh-tw', 'zh-cn' ), - array( 'en', 'User:JohnDoe/Monobook.css', 'es', 'zh-tw', 'zh-cn' ), - - array( 'zh-cn', 'Main_page', 'zh', 'zh-tw', 'zh-cn' ), - array( 'zh', 'MediaWiki:About', 'zh', 'zh-tw', 'zh-cn' ), - array( 'zh', 'MediaWiki:About/', 'zh', 'zh-tw', 'zh-cn' ), - array( 'de', 'MediaWiki:About/de', 'zh', 'zh-tw', 'zh-cn' ), - array( 'zh-cn', 'MediaWiki:About/zh-cn', 'zh', 'zh-tw', 'zh-cn' ), - array( 'zh-tw', 'MediaWiki:About/zh-tw', 'zh', 'zh-tw', 'zh-cn' ), - array( 'en', 'MediaWiki:Common.js', 'zh', 'zh-tw', 'zh-cn' ), - array( 'en', 'MediaWiki:Common.css', 'zh', 'zh-tw', 'zh-cn' ), - array( 'en', 'User:JohnDoe/Common.js', 'zh', 'zh-tw', 'zh-cn' ), - array( 'en', 'User:JohnDoe/Monobook.css', 'zh', 'zh-tw', 'zh-cn' ), - - array( 'zh-tw', 'Special:NewPages', 'es', 'zh-tw', 'zh-cn' ), - array( 'zh-tw', 'Special:NewPages', 'zh', 'zh-tw', 'zh-cn' ), - - ); - } -} diff --git a/tests/phpunit/includes/UserTest.php b/tests/phpunit/includes/UserTest.php deleted file mode 100644 index 7a424aef..00000000 --- a/tests/phpunit/includes/UserTest.php +++ /dev/null @@ -1,171 +0,0 @@ -savedGroupPermissions = $GLOBALS['wgGroupPermissions']; - $this->savedRevokedPermissions = $GLOBALS['wgRevokePermissions']; - - $this->setUpPermissionGlobals(); - $this->setUpUser(); - } - private function setUpPermissionGlobals() { - global $wgGroupPermissions, $wgRevokePermissions; - - # Data for regular $wgGroupPermissions test - $wgGroupPermissions['unittesters'] = array( - 'test' => true, - 'runtest' => true, - 'writetest' => false, - 'nukeworld' => false, - ); - $wgGroupPermissions['testwriters'] = array( - 'test' => true, - 'writetest' => true, - 'modifytest' => true, - ); - # Data for regular $wgRevokePermissions test - $wgRevokePermissions['formertesters'] = array( - 'runtest' => true, - ); - } - private function setUpUser() { - $this->user = new User; - $this->user->addGroup( 'unittesters' ); - } - - public function tearDown() { - parent::tearDown(); - - $GLOBALS['wgGroupPermissions'] = $this->savedGroupPermissions; - $GLOBALS['wgRevokePermissions'] = $this->savedRevokedPermissions; - } - - public function testGroupPermissions() { - $rights = User::getGroupPermissions( array( 'unittesters' ) ); - $this->assertContains( 'runtest', $rights ); - $this->assertNotContains( 'writetest', $rights ); - $this->assertNotContains( 'modifytest', $rights ); - $this->assertNotContains( 'nukeworld', $rights ); - - $rights = User::getGroupPermissions( array( 'unittesters', 'testwriters' ) ); - $this->assertContains( 'runtest', $rights ); - $this->assertContains( 'writetest', $rights ); - $this->assertContains( 'modifytest', $rights ); - $this->assertNotContains( 'nukeworld', $rights ); - } - public function testRevokePermissions() { - $rights = User::getGroupPermissions( array( 'unittesters', 'formertesters' ) ); - $this->assertNotContains( 'runtest', $rights ); - $this->assertNotContains( 'writetest', $rights ); - $this->assertNotContains( 'modifytest', $rights ); - $this->assertNotContains( 'nukeworld', $rights ); - } - - public function testUserPermissions() { - $rights = $this->user->getRights(); - $this->assertContains( 'runtest', $rights ); - $this->assertNotContains( 'writetest', $rights ); - $this->assertNotContains( 'modifytest', $rights ); - $this->assertNotContains( 'nukeworld', $rights ); - } - - /** - * @dataProvider provideGetGroupsWithPermission - */ - public function testGetGroupsWithPermission( $expected, $right ) { - $result = User::getGroupsWithPermission( $right ); - sort( $result ); - sort( $expected ); - - $this->assertEquals( $expected, $result, "Groups with permission $right" ); - } - - public function provideGetGroupsWithPermission() { - return array( - array( - array( 'unittesters', 'testwriters' ), - 'test' - ), - array( - array( 'unittesters' ), - 'runtest' - ), - array( - array( 'testwriters' ), - 'writetest' - ), - array( - array( 'testwriters' ), - 'modifytest' - ), - ); - } - - /** - * @dataProvider provideUserNames - */ - public function testIsValidUserName( $username, $result, $message ) { - $this->assertEquals( $this->user->isValidUserName( $username ), $result, $message ); - } - - public function provideUserNames() { - return array( - array( '', false, 'Empty string' ), - array( ' ', false, 'Blank space' ), - array( 'abcd', false, 'Starts with small letter' ), - array( 'Ab/cd', false, 'Contains slash' ), - array( 'Ab cd' , true, 'Whitespace' ), - array( '192.168.1.1', false, 'IP' ), - array( 'User:Abcd', false, 'Reserved Namespace' ), - array( '12abcd232' , true , 'Starts with Numbers' ), - array( '?abcd' , true, 'Start with ? mark' ), - array( '#abcd', false, 'Start with #' ), - array( 'Abcdകഖഗഘ', true, ' Mixed scripts' ), - array( 'ജോസ്‌തോമസ്', false, 'ZWNJ- Format control character' ), - array( 'Ab cd', false, ' Ideographic space' ), - ); - } - - /** - * Test, if for all rights a right- message exist, - * which is used on Special:ListGroupRights as help text - * Extensions and core - */ - public function testAllRightsWithMessage() { - //Getting all user rights, for core: User::$mCoreRights, for extensions: $wgAvailableRights - $allRights = User::getAllRights(); - $allMessageKeys = Language::getMessageKeysFor( 'en' ); - - $rightsWithMessage = array(); - foreach ( $allMessageKeys as $message ) { - // === 0: must be at beginning of string (position 0) - if ( strpos( $message, 'right-' ) === 0 ) { - $rightsWithMessage[] = substr( $message, strlen( 'right-' ) ); - } - } - - sort( $allRights ); - sort( $rightsWithMessage ); - - $this->assertEquals( - $allRights, - $rightsWithMessage, - 'Each user rights (core/extensions) has a corresponding right- message.' - ); - } -} diff --git a/tests/phpunit/includes/WebRequestTest.php b/tests/phpunit/includes/WebRequestTest.php deleted file mode 100644 index 1fc0b4b3..00000000 --- a/tests/phpunit/includes/WebRequestTest.php +++ /dev/null @@ -1,216 +0,0 @@ -assertEquals( $expected, $result, $description ); - } - - function provideDetectServer() { - return array( - array( - 'http://x', - array( - 'HTTP_HOST' => 'x' - ), - 'Host header' - ), - array( - 'https://x', - array( - 'HTTP_HOST' => 'x', - 'HTTPS' => 'on', - ), - 'Host header with secure' - ), - array( - 'http://x', - array( - 'HTTP_HOST' => 'x', - 'SERVER_PORT' => 80, - ), - 'Default SERVER_PORT', - ), - array( - 'http://x', - array( - 'HTTP_HOST' => 'x', - 'HTTPS' => 'off', - ), - 'Secure off' - ), - array( - 'http://y', - array( - 'SERVER_NAME' => 'y', - ), - 'Server name' - ), - array( - 'http://x', - array( - 'HTTP_HOST' => 'x', - 'SERVER_NAME' => 'y', - ), - 'Host server name precedence' - ), - array( - 'http://[::1]:81', - array( - 'HTTP_HOST' => '[::1]', - 'SERVER_NAME' => '::1', - 'SERVER_PORT' => '81', - ), - 'Apache bug 26005' - ), - array( - 'http://localhost', - array( - 'SERVER_NAME' => '[2001' - ), - 'Kind of like lighttpd per commit message in MW r83847', - ), - array( - 'http://[2a01:e35:2eb4:1::2]:777', - array( - 'SERVER_NAME' => '[2a01:e35:2eb4:1::2]:777' - ), - 'Possible lighttpd environment per bug 14977 comment 13', - ), - ); - } - - /** - * @dataProvider provideGetIP - */ - function testGetIP( $expected, $input, $squid, $private, $description ) { - global $wgSquidServersNoPurge, $wgUsePrivateIPs; - $_SERVER = $input; - $wgSquidServersNoPurge = $squid; - $wgUsePrivateIPs = $private; - $request = new WebRequest(); - $result = $request->getIP(); - $this->assertEquals( $expected, $result, $description ); - } - - function provideGetIP() { - return array( - array( - '127.0.0.1', - array( - 'REMOTE_ADDR' => '127.0.0.1' - ), - array(), - false, - 'Simple IPv4' - ), - array( - '::1', - array( - 'REMOTE_ADDR' => '::1' - ), - array(), - false, - 'Simple IPv6' - ), - array( - '12.0.0.3', - array( - 'REMOTE_ADDR' => '12.0.0.1', - 'HTTP_X_FORWARDED_FOR' => '12.0.0.3, 12.0.0.2' - ), - array( '12.0.0.1', '12.0.0.2' ), - false, - 'With X-Forwaded-For' - ), - array( - '12.0.0.1', - array( - 'REMOTE_ADDR' => '12.0.0.1', - 'HTTP_X_FORWARDED_FOR' => '12.0.0.3, 12.0.0.2' - ), - array(), - false, - 'With X-Forwaded-For and disallowed server' - ), - array( - '12.0.0.2', - array( - 'REMOTE_ADDR' => '12.0.0.1', - 'HTTP_X_FORWARDED_FOR' => '12.0.0.3, 12.0.0.2' - ), - array( '12.0.0.1' ), - false, - 'With multiple X-Forwaded-For and only one allowed server' - ), - array( - '12.0.0.2', - array( - 'REMOTE_ADDR' => '12.0.0.2', - 'HTTP_X_FORWARDED_FOR' => '10.0.0.3, 12.0.0.2' - ), - array( '12.0.0.1', '12.0.0.2' ), - false, - 'With X-Forwaded-For and private IP' - ), - array( - '10.0.0.3', - array( - 'REMOTE_ADDR' => '12.0.0.2', - 'HTTP_X_FORWARDED_FOR' => '10.0.0.3, 12.0.0.2' - ), - array( '12.0.0.1', '12.0.0.2' ), - true, - 'With X-Forwaded-For and private IP (allowed)' - ), - ); - } - - /** - * @expectedException MWException - */ - function testGetIpLackOfRemoteAddrThrowAnException() { - $request = new WebRequest(); - # Next call throw an exception about lacking an IP - $request->getIP(); - } - - function languageProvider() { - return array( - array( '', array(), 'Empty Accept-Language header' ), - array( 'en', array( 'en' => 1 ), 'One language' ), - array( 'en, ar', array( 'en' => 1, 'ar' => 1 ), 'Two languages listed in appearance order.' ), - array( 'zh-cn,zh-tw', array( 'zh-cn' => 1, 'zh-tw' => 1 ), 'Two equally prefered languages, listed in appearance order per rfc3282. Checks c9119' ), - array( 'es, en; q=0.5', array( 'es' => 1, 'en' => '0.5' ), 'Spanish as first language and English and second' ), - array( 'en; q=0.5, es', array( 'es' => 1, 'en' => '0.5' ), 'Less prefered language first' ), - array( 'fr, en; q=0.5, es', array( 'fr' => 1, 'es' => 1, 'en' => '0.5' ), 'Three languages' ), - array( 'en; q=0.5, es', array( 'es' => 1, 'en' => '0.5' ), 'Two languages' ), - array( 'en, zh;q=0', array( 'en' => 1 ), "It's Chinese to me" ), - array( 'es; q=1, pt;q=0.7, it; q=0.6, de; q=0.1, ru;q=0', array( 'es' => '1', 'pt' => '0.7', 'it' => '0.6', 'de' => '0.1' ), 'Preference for romance languages' ), - array( 'en-gb, en-us; q=1', array( 'en-gb' => 1, 'en-us' => '1' ), 'Two equally prefered English variants' ), - ); - } - - /** - * @dataProvider languageProvider - */ - function testAcceptLang($acceptLanguageHeader, $expectedLanguages, $description) { - $_SERVER = array( 'HTTP_ACCEPT_LANGUAGE' => $acceptLanguageHeader ); - $request = new WebRequest(); - $this->assertSame( $request->getAcceptLang(), $expectedLanguages, $description); - } -} diff --git a/tests/phpunit/includes/WikiPageTest.php b/tests/phpunit/includes/WikiPageTest.php deleted file mode 100644 index 0e1e1ce8..00000000 --- a/tests/phpunit/includes/WikiPageTest.php +++ /dev/null @@ -1,784 +0,0 @@ -tablesUsed = array_merge ( $this->tablesUsed, - array( 'page', - 'revision', - 'text', - - 'recentchanges', - 'logging', - - 'page_props', - 'pagelinks', - 'categorylinks', - 'langlinks', - 'externallinks', - 'imagelinks', - 'templatelinks', - 'iwlinks' ) ); - } - - public function setUp() { - parent::setUp(); - $this->pages_to_delete = array(); - } - - public function tearDown() { - foreach ( $this->pages_to_delete as $p ) { - /* @var $p WikiPage */ - - try { - if ( $p->exists() ) { - $p->doDeleteArticle( "testing done." ); - } - } catch ( MWException $ex ) { - // fail silently - } - } - parent::tearDown(); - } - - protected function newPage( $title ) { - if ( is_string( $title ) ) $title = Title::newFromText( $title ); - - $p = new WikiPage( $title ); - - $this->pages_to_delete[] = $p; - - return $p; - } - - protected function createPage( $page, $text, $model = null ) { - if ( is_string( $page ) ) $page = Title::newFromText( $page ); - if ( $page instanceof Title ) $page = $this->newPage( $page ); - - $page->doEdit( $text, "testing", EDIT_NEW ); - - return $page; - } - - public function testDoEdit() { - $title = Title::newFromText( "WikiPageTest_testDoEdit" ); - - $page = $this->newPage( $title ); - - $text = "[[Lorem ipsum]] dolor sit amet, consetetur sadipscing elitr, sed diam " - . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat."; - - $page->doEdit( $text, "testing 1" ); - - $this->assertTrue( $title->exists(), "Title object should indicate that the page now exists" ); - $this->assertTrue( $page->exists(), "WikiPage object should indicate that the page now exists" ); - - $id = $page->getId(); - - # ------------------------ - $page = new WikiPage( $title ); - - $retrieved = $page->getText(); - $this->assertEquals( $text, $retrieved, 'retrieved text doesn\'t equal original' ); - - # ------------------------ - $text = "At vero eos et accusam et justo duo [[dolores]] et ea rebum. " - . "Stet clita kasd [[gubergren]], no sea takimata sanctus est."; - - $page->doEdit( $text, "testing 2" ); - - # ------------------------ - $page = new WikiPage( $title ); - - $retrieved = $page->getText(); - $this->assertEquals( $text, $retrieved, 'retrieved text doesn\'t equal original' ); - - # ------------------------ - $dbr = wfGetDB( DB_SLAVE ); - $res = $dbr->select( 'pagelinks', '*', array( 'pl_from' => $id ) ); - $n = $res->numRows(); - $res->free(); - - $this->assertEquals( 2, $n, 'pagelinks should contain two links from the page' ); - } - - public function testDoQuickEdit() { - global $wgUser; - - $page = $this->createPage( "WikiPageTest_testDoQuickEdit", "original text" ); - - $text = "quick text"; - $page->doQuickEdit( $text, $wgUser, "testing q" ); - - # --------------------- - $page = new WikiPage( $page->getTitle() ); - $this->assertEquals( $text, $page->getText() ); - } - - public function testDoDeleteArticle() { - $page = $this->createPage( "WikiPageTest_testDoDeleteArticle", "[[original text]] foo" ); - $id = $page->getId(); - - $page->doDeleteArticle( "testing deletion" ); - - $this->assertFalse( $page->exists(), "WikiPage::exists should return false after page was deleted" ); - $this->assertFalse( $page->getText(), "WikiPage::getText should return false after page was deleted" ); - - $t = Title::newFromText( $page->getTitle()->getPrefixedText() ); - $this->assertFalse( $t->exists(), "Title::exists should return false after page was deleted" ); - - # ------------------------ - $dbr = wfGetDB( DB_SLAVE ); - $res = $dbr->select( 'pagelinks', '*', array( 'pl_from' => $id ) ); - $n = $res->numRows(); - $res->free(); - - $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' ); - } - - public function testDoDeleteUpdates() { - $page = $this->createPage( "WikiPageTest_testDoDeleteArticle", "[[original text]] foo" ); - $id = $page->getId(); - - $page->doDeleteUpdates( $id ); - - # ------------------------ - $dbr = wfGetDB( DB_SLAVE ); - $res = $dbr->select( 'pagelinks', '*', array( 'pl_from' => $id ) ); - $n = $res->numRows(); - $res->free(); - - $this->assertEquals( 0, $n, 'pagelinks should contain no more links from the page' ); - } - - public function testGetRevision() { - $page = $this->newPage( "WikiPageTest_testGetRevision" ); - - $rev = $page->getRevision(); - $this->assertNull( $rev ); - - # ----------------- - $this->createPage( $page, "some text" ); - - $rev = $page->getRevision(); - - $this->assertEquals( $page->getLatest(), $rev->getId() ); - $this->assertEquals( "some text", $rev->getText() ); - } - - public function testGetText() { - $page = $this->newPage( "WikiPageTest_testGetText" ); - - $text = $page->getText(); - $this->assertFalse( $text ); - - # ----------------- - $this->createPage( $page, "some text" ); - - $text = $page->getText(); - $this->assertEquals( "some text", $text ); - } - - public function testGetRawText() { - $page = $this->newPage( "WikiPageTest_testGetRawText" ); - - $text = $page->getRawText(); - $this->assertFalse( $text ); - - # ----------------- - $this->createPage( $page, "some text" ); - - $text = $page->getRawText(); - $this->assertEquals( "some text", $text ); - } - - - public function testExists() { - $page = $this->newPage( "WikiPageTest_testExists" ); - $this->assertFalse( $page->exists() ); - - # ----------------- - $this->createPage( $page, "some text" ); - $this->assertTrue( $page->exists() ); - - $page = new WikiPage( $page->getTitle() ); - $this->assertTrue( $page->exists() ); - - # ----------------- - $page->doDeleteArticle( "done testing" ); - $this->assertFalse( $page->exists() ); - - $page = new WikiPage( $page->getTitle() ); - $this->assertFalse( $page->exists() ); - } - - public function dataHasViewableContent() { - return array( - array( 'WikiPageTest_testHasViewableContent', false, true ), - array( 'Special:WikiPageTest_testHasViewableContent', false ), - array( 'MediaWiki:WikiPageTest_testHasViewableContent', false ), - array( 'Special:Userlogin', true ), - array( 'MediaWiki:help', true ), - ); - } - - /** - * @dataProvider dataHasViewableContent - */ - public function testHasViewableContent( $title, $viewable, $create = false ) { - $page = $this->newPage( $title ); - $this->assertEquals( $viewable, $page->hasViewableContent() ); - - if ( $create ) { - $this->createPage( $page, "some text" ); - $this->assertTrue( $page->hasViewableContent() ); - - $page = new WikiPage( $page->getTitle() ); - $this->assertTrue( $page->hasViewableContent() ); - } - } - - public function dataGetRedirectTarget() { - return array( - array( 'WikiPageTest_testGetRedirectTarget_1', "hello world", null ), - array( 'WikiPageTest_testGetRedirectTarget_2', "#REDIRECT [[hello world]]", "Hello world" ), - ); - } - - /** - * @dataProvider dataGetRedirectTarget - */ - public function testGetRedirectTarget( $title, $text, $target ) { - $page = $this->createPage( $title, $text ); - - # now, test the actual redirect - $t = $page->getRedirectTarget(); - $this->assertEquals( $target, is_null( $t ) ? null : $t->getPrefixedText() ); - } - - /** - * @dataProvider dataGetRedirectTarget - */ - public function testIsRedirect( $title, $text, $target ) { - $page = $this->createPage( $title, $text ); - $this->assertEquals( !is_null( $target ), $page->isRedirect() ); - } - - public function dataIsCountable() { - return array( - - // any - array( 'WikiPageTest_testIsCountable', - '', - 'any', - true - ), - array( 'WikiPageTest_testIsCountable', - 'Foo', - 'any', - true - ), - - // comma - array( 'WikiPageTest_testIsCountable', - 'Foo', - 'comma', - false - ), - array( 'WikiPageTest_testIsCountable', - 'Foo, bar', - 'comma', - true - ), - - // link - array( 'WikiPageTest_testIsCountable', - 'Foo', - 'link', - false - ), - array( 'WikiPageTest_testIsCountable', - 'Foo [[bar]]', - 'link', - true - ), - - // redirects - array( 'WikiPageTest_testIsCountable', - '#REDIRECT [[bar]]', - 'any', - false - ), - array( 'WikiPageTest_testIsCountable', - '#REDIRECT [[bar]]', - 'comma', - false - ), - array( 'WikiPageTest_testIsCountable', - '#REDIRECT [[bar]]', - 'link', - false - ), - - // not a content namespace - array( 'Talk:WikiPageTest_testIsCountable', - 'Foo', - 'any', - false - ), - array( 'Talk:WikiPageTest_testIsCountable', - 'Foo, bar', - 'comma', - false - ), - array( 'Talk:WikiPageTest_testIsCountable', - 'Foo [[bar]]', - 'link', - false - ), - - // not a content namespace, different model - array( 'MediaWiki:WikiPageTest_testIsCountable.js', - 'Foo', - 'any', - false - ), - array( 'MediaWiki:WikiPageTest_testIsCountable.js', - 'Foo, bar', - 'comma', - false - ), - array( 'MediaWiki:WikiPageTest_testIsCountable.js', - 'Foo [[bar]]', - 'link', - false - ), - ); - } - - - /** - * @dataProvider dataIsCountable - */ - public function testIsCountable( $title, $text, $mode, $expected ) { - global $wgArticleCountMethod; - - $old = $wgArticleCountMethod; - $wgArticleCountMethod = $mode; - - $page = $this->createPage( $title, $text ); - $editInfo = $page->prepareTextForEdit( $page->getText() ); - - $v = $page->isCountable(); - $w = $page->isCountable( $editInfo ); - $wgArticleCountMethod = $old; - - $this->assertEquals( $expected, $v, "isCountable( null ) returned unexpected value " . var_export( $v, true ) - . " instead of " . var_export( $expected, true ) . " in mode `$mode` for text \"$text\"" ); - - $this->assertEquals( $expected, $w, "isCountable( \$editInfo ) returned unexpected value " . var_export( $v, true ) - . " instead of " . var_export( $expected, true ) . " in mode `$mode` for text \"$text\"" ); - } - - public function dataGetParserOutput() { - return array( - array("hello ''world''\n", "

hello world

"), - // @todo: more...? - ); - } - - /** - * @dataProvider dataGetParserOutput - */ - public function testGetParserOutput( $text, $expectedHtml ) { - $page = $this->createPage( 'WikiPageTest_testGetParserOutput', $text ); - - $opt = new ParserOptions(); - $po = $page->getParserOutput( $opt ); - $text = $po->getText(); - - $text = trim( preg_replace( '//sm', '', $text ) ); # strip injected comments - $text = preg_replace( '!\s*(

)!sm', '\1', $text ); # don't let tidy confuse us - - $this->assertEquals( $expectedHtml, $text ); - return $po; - } - - static $sections = - - "Intro - -== stuff == -hello world - -== test == -just a test - -== foo == -more stuff -"; - - - public function dataReplaceSection() { - return array( - array( 'WikiPageTest_testReplaceSection', - WikiPageTest::$sections, - "0", - "No more", - null, - trim( preg_replace( '/^Intro/sm', 'No more', WikiPageTest::$sections ) ) - ), - array( 'WikiPageTest_testReplaceSection', - WikiPageTest::$sections, - "", - "No more", - null, - "No more" - ), - array( 'WikiPageTest_testReplaceSection', - WikiPageTest::$sections, - "2", - "== TEST ==\nmore fun", - null, - trim( preg_replace( '/^== test ==.*== foo ==/sm', "== TEST ==\nmore fun\n\n== foo ==", WikiPageTest::$sections ) ) - ), - array( 'WikiPageTest_testReplaceSection', - WikiPageTest::$sections, - "8", - "No more", - null, - trim( WikiPageTest::$sections ) - ), - array( 'WikiPageTest_testReplaceSection', - WikiPageTest::$sections, - "new", - "No more", - "New", - trim( WikiPageTest::$sections ) . "\n\n== New ==\n\nNo more" - ), - ); - } - - /** - * @dataProvider dataReplaceSection - */ - public function testReplaceSection( $title, $text, $section, $with, $sectionTitle, $expected ) { - $page = $this->createPage( $title, $text ); - $text = $page->replaceSection( $section, $with, $sectionTitle ); - $text = trim( $text ); - - $this->assertEquals( $expected, $text ); - } - - /* @todo FIXME: fix this! - public function testGetUndoText() { - global $wgDiff3; - - wfSuppressWarnings(); - $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 ); - wfRestoreWarnings(); - - if( !$haveDiff3 ) { - $this->markTestSkipped( "diff3 not installed or not found" ); - return; - } - - $text = "one"; - $page = $this->createPage( "WikiPageTest_testGetUndoText", $text ); - $rev1 = $page->getRevision(); - - $text .= "\n\ntwo"; - $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ), "adding section two"); - $rev2 = $page->getRevision(); - - $text .= "\n\nthree"; - $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ), "adding section three"); - $rev3 = $page->getRevision(); - - $text .= "\n\nfour"; - $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ), "adding section four"); - $rev4 = $page->getRevision(); - - $text .= "\n\nfive"; - $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ), "adding section five"); - $rev5 = $page->getRevision(); - - $text .= "\n\nsix"; - $page->doEditContent( ContentHandler::makeContent( $text, $page->getTitle() ), "adding section six"); - $rev6 = $page->getRevision(); - - $undo6 = $page->getUndoText( $rev6 ); - if ( $undo6 === false ) $this->fail( "getUndoText failed for rev6" ); - $this->assertEquals( "one\n\ntwo\n\nthree\n\nfour\n\nfive", $undo6 ); - - $undo3 = $page->getUndoText( $rev4, $rev2 ); - if ( $undo3 === false ) $this->fail( "getUndoText failed for rev4..rev2" ); - $this->assertEquals( "one\n\ntwo\n\nfive", $undo3 ); - - $undo2 = $page->getUndoText( $rev2 ); - if ( $undo2 === false ) $this->fail( "getUndoText failed for rev2" ); - $this->assertEquals( "one\n\nfive", $undo2 ); - } - */ - - /** - * @todo FIXME: this is a better rollback test than the one below, but it keeps failing in jenkins for some reason. - */ - public function broken_testDoRollback() { - $admin = new User(); - $admin->setName("Admin"); - - $text = "one"; - $page = $this->newPage( "WikiPageTest_testDoRollback" ); - $page->doEdit( $text, "section one", EDIT_NEW, false, $admin ); - - $user1 = new User(); - $user1->setName( "127.0.1.11" ); - $text .= "\n\ntwo"; - $page = new WikiPage( $page->getTitle() ); - $page->doEdit( $text, "adding section two", 0, false, $user1 ); - - $user2 = new User(); - $user2->setName( "127.0.2.13" ); - $text .= "\n\nthree"; - $page = new WikiPage( $page->getTitle() ); - $page->doEdit( $text, "adding section three", 0, false, $user2 ); - - # we are having issues with doRollback spuriously failing. apparently the last revision somehow goes missing - # or not committed under some circumstances. so, make sure the last revision has the right user name. - $dbr = wfGetDB( DB_SLAVE ); - $this->assertEquals( 3, Revision::countByPageId( $dbr, $page->getId() ) ); - - $page = new WikiPage( $page->getTitle() ); - $rev3 = $page->getRevision(); - $this->assertEquals( '127.0.2.13', $rev3->getUserText() ); - - $rev2 = $rev3->getPrevious(); - $this->assertEquals( '127.0.1.11', $rev2->getUserText() ); - - $rev1 = $rev2->getPrevious(); - $this->assertEquals( 'Admin', $rev1->getUserText() ); - - # now, try the actual rollback - $admin->addGroup( "sysop" ); #XXX: make the test user a sysop... - $token = $admin->getEditToken( array( $page->getTitle()->getPrefixedText(), $user2->getName() ), null ); - $errors = $page->doRollback( $user2->getName(), "testing revert", $token, false, $details, $admin ); - - if ( $errors ) { - $this->fail( "Rollback failed:\n" . print_r( $errors, true ) . ";\n" . print_r( $details, true ) ); - } - - $page = new WikiPage( $page->getTitle() ); - $this->assertEquals( $rev2->getSha1(), $page->getRevision()->getSha1(), "rollback did not revert to the correct revision" ); - $this->assertEquals( "one\n\ntwo", $page->getText() ); - } - - /** - * @todo FIXME: the above rollback test is better, but it keeps failing in jenkins for some reason. - */ - public function testDoRollback() { - $admin = new User(); - $admin->setName("Admin"); - - $text = "one"; - $page = $this->newPage( "WikiPageTest_testDoRollback" ); - $page->doEdit( $text, "section one", EDIT_NEW, false, $admin ); - $rev1 = $page->getRevision(); - - $user1 = new User(); - $user1->setName( "127.0.1.11" ); - $text .= "\n\ntwo"; - $page = new WikiPage( $page->getTitle() ); - $page->doEdit( $text, "adding section two", 0, false, $user1 ); - - # now, try the rollback - $admin->addGroup( "sysop" ); #XXX: make the test user a sysop... - $token = $admin->getEditToken( array( $page->getTitle()->getPrefixedText(), $user1->getName() ), null ); - $errors = $page->doRollback( $user1->getName(), "testing revert", $token, false, $details, $admin ); - - if ( $errors ) { - $this->fail( "Rollback failed:\n" . print_r( $errors, true ) . ";\n" . print_r( $details, true ) ); - } - - $page = new WikiPage( $page->getTitle() ); - $this->assertEquals( $rev1->getSha1(), $page->getRevision()->getSha1(), "rollback did not revert to the correct revision" ); - $this->assertEquals( "one", $page->getText() ); - } - - public function dataGetAutosummary( ) { - return array( - array( - 'Hello there, world!', - '#REDIRECT [[Foo]]', - 0, - '/^Redirected page .*Foo/' - ), - - array( - null, - 'Hello world!', - EDIT_NEW, - '/^Created page .*Hello/' - ), - - array( - 'Hello there, world!', - '', - 0, - '/^Blanked/' - ), - - array( - 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut - labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et - ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.', - 'Hello world!', - 0, - '/^Replaced .*Hello/' - ), - - array( - 'foo', - 'bar', - 0, - '/^$/' - ), - ); - } - - /** - * @dataProvider dataGetAutoSummary - */ - public function testGetAutosummary( $old, $new, $flags, $expected ) { - $page = $this->newPage( "WikiPageTest_testGetAutosummary" ); - - $summary = $page->getAutosummary( $old, $new, $flags ); - - $this->assertTrue( (bool)preg_match( $expected, $summary ), "Autosummary didn't match expected pattern $expected: $summary" ); - } - - public function dataGetAutoDeleteReason( ) { - return array( - array( - array(), - false, - false - ), - - array( - array( - array( "first edit", null ), - ), - "/first edit.*only contributor/", - false - ), - - array( - array( - array( "first edit", null ), - array( "second edit", null ), - ), - "/second edit.*only contributor/", - true - ), - - array( - array( - array( "first edit", "127.0.2.22" ), - array( "second edit", "127.0.3.33" ), - ), - "/second edit/", - true - ), - - array( - array( - array( "first edit: " - . "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam " - . " nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. " - . "At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea " - . "takimata sanctus est Lorem ipsum dolor sit amet.'", null ), - ), - '/first edit:.*\.\.\."/', - false - ), - - array( - array( - array( "first edit", "127.0.2.22" ), - array( "", "127.0.3.33" ), - ), - "/before blanking.*first edit/", - true - ), - - ); - } - - /** - * @dataProvider dataGetAutoDeleteReason - */ - public function testGetAutoDeleteReason( $edits, $expectedResult, $expectedHistory ) { - global $wgUser; - - $page = $this->newPage( "WikiPageTest_testGetAutoDeleteReason" ); - - $c = 1; - - foreach ( $edits as $edit ) { - $user = new User(); - - if ( !empty( $edit[1] ) ) $user->setName( $edit[1] ); - else $user = $wgUser; - - $page->doEdit( $edit[0], "test edit $c", $c < 2 ? EDIT_NEW : 0, false, $user ); - - $c += 1; - } - - $reason = $page->getAutoDeleteReason( $hasHistory ); - - if ( is_bool( $expectedResult ) || is_null( $expectedResult ) ) $this->assertEquals( $expectedResult, $reason ); - else $this->assertTrue( (bool)preg_match( $expectedResult, $reason ), "Autosummary didn't match expected pattern $expectedResult: $reason" ); - - $this->assertEquals( $expectedHistory, $hasHistory, "expected \$hasHistory to be " . var_export( $expectedHistory, true ) ); - - $page->doDeleteArticle( "done" ); - } - - public function dataPreSaveTransform() { - return array( - array( 'hello this is ~~~', - "hello this is [[Special:Contributions/127.0.0.1|127.0.0.1]]", - ), - array( 'hello \'\'this\'\' is ~~~', - 'hello \'\'this\'\' is ~~~', - ), - ); - } - - /** - * @dataProvider dataPreSaveTransform - */ - public function testPreSaveTransform( $text, $expected ) { - $this->hideDeprecated( 'WikiPage::preSaveTransform' ); - $user = new User(); - $user->setName("127.0.0.1"); - - $page = $this->newPage( "WikiPageTest_testPreloadTransform" ); - $text = $page->preSaveTransform( $text, $user ); - - $this->assertEquals( $expected, $text ); - } - -} - diff --git a/tests/phpunit/includes/XmlJsTest.php b/tests/phpunit/includes/XmlJsTest.php deleted file mode 100644 index c5b411fb..00000000 --- a/tests/phpunit/includes/XmlJsTest.php +++ /dev/null @@ -1,9 +0,0 @@ -assertNull( $obj->value ); - $obj = new XmlJsCode( '' ); - $this->assertSame( $obj->value, '' ); - } -} diff --git a/tests/phpunit/includes/XmlSelectTest.php b/tests/phpunit/includes/XmlSelectTest.php deleted file mode 100644 index 2407c151..00000000 --- a/tests/phpunit/includes/XmlSelectTest.php +++ /dev/null @@ -1,139 +0,0 @@ -select = new XmlSelect(); - } - protected function tearDown() { - $this->select = null; - } - - ### START OF TESTS ### - - public function testConstructWithoutParameters() { - $this->assertEquals( '', $this->select->getHTML() ); - } - - /** - * Parameters are $name (false), $id (false), $default (false) - * @dataProvider provideConstructionParameters - */ - public function testConstructParameters( $name, $id, $default, $expected ) { - $this->select = new XmlSelect( $name, $id, $default ); - $this->assertEquals( $expected, $this->select->getHTML() ); - } - - /** - * Provide parameters for testConstructParameters() which use three - * parameters: - * - $name (default: false) - * - $id (default: false) - * - $default (default: false) - * Provides a fourth parameters representing the expected HTML output - * - */ - public function provideConstructionParameters() { - return array( - /** - * Values are set following a 3-bit Gray code where two successive - * values differ by only one value. - * See http://en.wikipedia.org/wiki/Gray_code - */ - # $name $id $default - array( false , false, false, '' ), - array( false , false, 'foo', '' ), - array( false , 'id' , 'foo', '' ), - array( false , 'id' , false, '' ), - array( 'name', 'id' , false, '' ), - array( 'name', 'id' , 'foo', '' ), - array( 'name', false, 'foo', '' ), - array( 'name', false, false, '' ), - ); - } - - # Begin XmlSelect::addOption() similar to Xml::option - public function testAddOption() { - $this->select->addOption( 'foo' ); - $this->assertEquals( '', $this->select->getHTML() ); - } - public function testAddOptionWithDefault() { - $this->select->addOption( 'foo', true ); - $this->assertEquals( '', $this->select->getHTML() ); - } - public function testAddOptionWithFalse() { - $this->select->addOption( 'foo', false ); - $this->assertEquals( '', $this->select->getHTML() ); - } - public function testAddOptionWithValueZero() { - $this->select->addOption( 'foo', 0 ); - $this->assertEquals( '', $this->select->getHTML() ); - } - # End XmlSelect::addOption() similar to Xml::option - - public function testSetDefault() { - $this->select->setDefault( 'bar1' ); - $this->select->addOption( 'foo1' ); - $this->select->addOption( 'bar1' ); - $this->select->addOption( 'foo2' ); - $this->assertEquals( -'', $this->select->getHTML() ); - } - - /** - * Adding default later on should set the correct selection or - * raise an exception. - * To handle this, we need to render the options in getHtml() - */ - public function testSetDefaultAfterAddingOptions() { - $this->select->addOption( 'foo1' ); - $this->select->addOption( 'bar1' ); - $this->select->addOption( 'foo2' ); - $this->select->setDefault( 'bar1' ); # setting default after adding options - $this->assertEquals( -'', $this->select->getHTML() ); - } - - public function testGetAttributes() { - # create some attributes - $this->select->setAttribute( 'dummy', 0x777 ); - $this->select->setAttribute( 'string', 'euro €' ); - $this->select->setAttribute( 1911, 'razor' ); - - # verify we can retrieve them - $this->assertEquals( - $this->select->getAttribute( 'dummy' ), - 0x777 - ); - $this->assertEquals( - $this->select->getAttribute( 'string' ), - 'euro €' - ); - $this->assertEquals( - $this->select->getAttribute( 1911 ), - 'razor' - ); - - # inexistant keys should give us 'null' - $this->assertEquals( - $this->select->getAttribute( 'I DO NOT EXIT' ), - null - ); - - # verify string / integer - $this->assertEquals( - $this->select->getAttribute( '1911' ), - 'razor' - ); - $this->assertEquals( - $this->select->getAttribute( 'dummy' ), - 0x777 - ); - } -} diff --git a/tests/phpunit/includes/XmlTest.php b/tests/phpunit/includes/XmlTest.php deleted file mode 100644 index 93ed3dc7..00000000 --- a/tests/phpunit/includes/XmlTest.php +++ /dev/null @@ -1,342 +0,0 @@ -getNamespaces(); - $wgContLang->setNamespaces( array( - -2 => 'Media', - -1 => 'Special', - 0 => '', - 1 => 'Talk', - 2 => 'User', - 3 => 'User_talk', - 4 => 'MyWiki', - 5 => 'MyWiki_Talk', - 6 => 'File', - 7 => 'File_talk', - 8 => 'MediaWiki', - 9 => 'MediaWiki_talk', - 10 => 'Template', - 11 => 'Template_talk', - 100 => 'Custom', - 101 => 'Custom_talk', - ) ); - } - - public function tearDown() { - global $wgLang, $wgContLang; - $wgLang = self::$oldLang; - - $wgContLang->setNamespaces( self::$oldNamespaces ); - } - - public function testExpandAttributes() { - $this->assertNull( Xml::expandAttributes(null), - 'Converting a null list of attributes' - ); - $this->assertEquals( '', Xml::expandAttributes( array() ), - 'Converting an empty list of attributes' - ); - } - - public function testExpandAttributesException() { - $this->setExpectedException('MWException'); - Xml::expandAttributes('string'); - } - - function testElementOpen() { - $this->assertEquals( - '', - Xml::element( 'element', null, null ), - 'Opening element with no attributes' - ); - } - - function testElementEmpty() { - $this->assertEquals( - '', - Xml::element( 'element', null, '' ), - 'Terminated empty element' - ); - } - - function testElementInputCanHaveAValueOfZero() { - $this->assertEquals( - '', - Xml::input( 'name', false, 0 ), - 'Input with a value of 0 (bug 23797)' - ); - } - function testElementEscaping() { - $this->assertEquals( - 'hello <there> you & you', - Xml::element( 'element', null, 'hello you & you' ), - 'Element with no attributes and content that needs escaping' - ); - } - - public function testEscapeTagsOnly() { - $this->assertEquals( '"><', Xml::escapeTagsOnly( '"><' ), - 'replace " > and < with their HTML entitites' - ); - } - - function testElementAttributes() { - $this->assertEquals( - '="<>">', - Xml::element( 'element', array( 'key' => 'value', '<>' => '<>' ), null ), - 'Element attributes, keys are not escaped' - ); - } - - function testOpenElement() { - $this->assertEquals( - '', - Xml::openElement( 'element', array( 'k' => 'v' ) ), - 'openElement() shortcut' - ); - } - - function testCloseElement() { - $this->assertEquals( '', Xml::closeElement( 'element' ), 'closeElement() shortcut' ); - } - - /** - * @group Broken - */ - public function testDateMenu( ) { - $curYear = intval(gmdate('Y')); - $prevYear = $curYear - 1; - - $curMonth = intval(gmdate('n')); - $prevMonth = $curMonth - 1; - if( $prevMonth == 0 ) { $prevMonth = 12; } - $nextMonth = $curMonth + 1; - if( $nextMonth == 13 ) { $nextMonth = 1; } - - $this->assertEquals( - ' ', - Xml::dateMenu( 2011, 02 ), - "Date menu for february 2011" - ); - $this->assertEquals( - ' ', - Xml::dateMenu( 2011, -1), - "Date menu with negative month for 'All'" - ); - $this->assertEquals( - Xml::dateMenu( $curYear, $curMonth ), - Xml::dateMenu( '' , $curMonth ), - "Date menu year is the current one when not specified" - ); - - // @todo FIXME: next month can be in the next year - // test failing because it is now december - $this->assertEquals( - Xml::dateMenu( $prevYear, $nextMonth ), - Xml::dateMenu( '', $nextMonth ), - "Date menu next month is 11 months ago" - ); - - # @todo FIXME: Please note there is no year there! - $this->assertEquals( - ' ', - Xml::dateMenu( '', '' ), - "Date menu with neither year or month" - ); - } - - # - # textarea - # - function testTextareaNoContent() { - $this->assertEquals( - '', - Xml::textarea( 'name', '' ), - 'textarea() with not content' - ); - } - - function testTextareaAttribs() { - $this->assertEquals( - '', - Xml::textarea( 'name', '', 20, 10 ), - 'textarea() with custom attribs' - ); - } - - # - # input and label - # - function testLabelCreation() { - $this->assertEquals( - '', - Xml::label( 'name', 'id' ), - 'label() with no attribs' - ); - } - function testLabelAttributeCanOnlyBeClassOrTitle() { - $this->assertEquals( - '', - Xml::label( 'name', 'id', array( 'generated' => true ) ), - 'label() can not be given a generated attribute' - ); - $this->assertEquals( - '', - Xml::label( 'name', 'id', array( 'class' => 'nice' ) ), - 'label() can get a class attribute' - ); - $this->assertEquals( - '', - Xml::label( 'name', 'id', array( 'title' => 'nice tooltip' ) ), - 'label() can get a title attribute' - ); - $this->assertEquals( - '', - Xml::label( 'name', 'id', array( - 'generated' => true, - 'class' => 'nice', - 'title' => 'nice tooltip', - 'anotherattr' => 'value', - ) - ), - 'label() skip all attributes but "class" and "title"' - ); - } - - function testLanguageSelector() { - $select = Xml::languageSelector( 'en', true, null, - array( 'id' => 'testlang' ), wfMessage( 'yourlanguage' ) ); - $this->assertEquals( - '', - $select[0] - ); - } - - # - # JS - # - function testEscapeJsStringSpecialChars() { - $this->assertEquals( - '\\\\\r\n', - Xml::escapeJsString( "\\\r\n" ), - 'escapeJsString() with special characters' - ); - } - - function testEncodeJsVarBoolean() { - $this->assertEquals( - 'true', - Xml::encodeJsVar( true ), - 'encodeJsVar() with boolean' - ); - } - - function testEncodeJsVarNull() { - $this->assertEquals( - 'null', - Xml::encodeJsVar( null ), - 'encodeJsVar() with null' - ); - } - - function testEncodeJsVarArray() { - $this->assertEquals( - '["a",1]', - Xml::encodeJsVar( array( 'a', 1 ) ), - 'encodeJsVar() with array' - ); - $this->assertEquals( - '{"a":"a","b":1}', - Xml::encodeJsVar( array( 'a' => 'a', 'b' => 1 ) ), - 'encodeJsVar() with associative array' - ); - } - - function testEncodeJsVarObject() { - $this->assertEquals( - '{"a":"a","b":1}', - Xml::encodeJsVar( (object)array( 'a' => 'a', 'b' => 1 ) ), - 'encodeJsVar() with object' - ); - } - - function testEncodeJsVarInt() { - $this->assertEquals( - '123456', - Xml::encodeJsVar( 123456 ), - 'encodeJsVar() with int' - ); - } - - function testEncodeJsVarFloat() { - $this->assertEquals( - '1.23456', - Xml::encodeJsVar( 1.23456 ), - 'encodeJsVar() with float' - ); - } - - function testEncodeJsVarIntString() { - $this->assertEquals( - '"123456"', - Xml::encodeJsVar( '123456' ), - 'encodeJsVar() with int-like string' - ); - } - - function testEncodeJsVarFloatString() { - $this->assertEquals( - '"1.23456"', - Xml::encodeJsVar( '1.23456' ), - 'encodeJsVar() with float-like string' - ); - } -} diff --git a/tests/phpunit/includes/ZipDirectoryReaderTest.php b/tests/phpunit/includes/ZipDirectoryReaderTest.php deleted file mode 100644 index d90a6950..00000000 --- a/tests/phpunit/includes/ZipDirectoryReaderTest.php +++ /dev/null @@ -1,79 +0,0 @@ -zipDir = __DIR__ . '/../data/zip'; - } - - function zipCallback( $entry ) { - $this->entries[] = $entry; - } - - function readZipAssertError( $file, $error, $assertMessage ) { - $this->entries = array(); - $status = ZipDirectoryReader::read( "{$this->zipDir}/$file", array( $this, 'zipCallback' ) ); - $this->assertTrue( $status->hasMessage( $error ), $assertMessage ); - } - - function readZipAssertSuccess( $file, $assertMessage ) { - $this->entries = array(); - $status = ZipDirectoryReader::read( "{$this->zipDir}/$file", array( $this, 'zipCallback' ) ); - $this->assertTrue( $status->isOK(), $assertMessage ); - } - - function testEmpty() { - $this->readZipAssertSuccess( 'empty.zip', 'Empty zip' ); - } - - function testMultiDisk0() { - $this->readZipAssertError( 'split.zip', 'zip-unsupported', - 'Split zip error' ); - } - - function testNoSignature() { - $this->readZipAssertError( 'nosig.zip', 'zip-wrong-format', - 'No signature should give "wrong format" error' ); - } - - function testSimple() { - $this->readZipAssertSuccess( 'class.zip', 'Simple ZIP' ); - $this->assertEquals( $this->entries, array( array( - 'name' => 'Class.class', - 'mtime' => '20010115000000', - 'size' => 1, - ) ) ); - } - - function testBadCentralEntrySignature() { - $this->readZipAssertError( 'wrong-central-entry-sig.zip', 'zip-bad', - 'Bad central entry error' ); - } - - function testTrailingBytes() { - $this->readZipAssertError( 'trail.zip', 'zip-bad', - 'Trailing bytes error' ); - } - - function testWrongCDStart() { - $this->readZipAssertError( 'wrong-cd-start-disk.zip', 'zip-unsupported', - 'Wrong CD start disk error' ); - } - - - function testCentralDirectoryGap() { - $this->readZipAssertError( 'cd-gap.zip', 'zip-bad', - 'CD gap error' ); - } - - function testCentralDirectoryTruncated() { - $this->readZipAssertError( 'cd-truncated.zip', 'zip-bad', - 'CD truncated error (should hit unpack() overrun)' ); - } - - function testLooksLikeZip64() { - $this->readZipAssertError( 'looks-like-zip64.zip', 'zip-unsupported', - 'A file which looks like ZIP64 but isn\'t, should give error' ); - } -} diff --git a/tests/phpunit/includes/api/ApiBlockTest.php b/tests/phpunit/includes/api/ApiBlockTest.php deleted file mode 100644 index 5dfceee8..00000000 --- a/tests/phpunit/includes/api/ApiBlockTest.php +++ /dev/null @@ -1,117 +0,0 @@ -doLogin(); - } - - function getTokens() { - return $this->getTokenList( self::$users['sysop'] ); - } - - function addDBData() { - $user = User::newFromName( 'UTApiBlockee' ); - - if ( $user->getId() == 0 ) { - $user->addToDatabase(); - $user->setPassword( 'UTApiBlockeePassword' ); - - $user->saveSettings(); - } - } - - /** - * This test has probably always been broken and use an invalid token - * Bug tracking brokenness is https://bugzilla.wikimedia.org/35646 - * - * Root cause is https://gerrit.wikimedia.org/r/3434 - * Which made the Block/Unblock API to actually verify the token - * previously always considered valid (bug 34212). - */ - function testMakeNormalBlock() { - - $data = $this->getTokens(); - - $user = User::newFromName( 'UTApiBlockee' ); - - if ( !$user->getId() ) { - $this->markTestIncomplete( "The user UTApiBlockee does not exist" ); - } - - if( !isset( $data[0]['query']['pages'] ) ) { - $this->markTestIncomplete( "No block token found" ); - } - - $keys = array_keys( $data[0]['query']['pages'] ); - $key = array_pop( $keys ); - $pageinfo = $data[0]['query']['pages'][$key]; - - $data = $this->doApiRequest( array( - 'action' => 'block', - 'user' => 'UTApiBlockee', - 'reason' => 'Some reason', - 'token' => $pageinfo['blocktoken'] ), null, false, self::$users['sysop']->user ); - - $block = Block::newFromTarget('UTApiBlockee'); - - $this->assertTrue( !is_null( $block ), 'Block is valid' ); - - $this->assertEquals( 'UTApiBlockee', (string)$block->getTarget() ); - $this->assertEquals( 'Some reason', $block->mReason ); - $this->assertEquals( 'infinity', $block->mExpiry ); - - } - - /** - * @dataProvider provideBlockUnblockAction - */ - function testGetTokenUsingABlockingAction( $action ) { - $data = $this->doApiRequest( - array( - 'action' => $action, - 'user' => 'UTApiBlockee', - 'gettoken' => '' ), - null, - false, - self::$users['sysop']->user - ); - $this->assertEquals( 34, strlen( $data[0][$action]["{$action}token"] ) ); - } - - /** - * Attempting to block without a token should give a UsageException with - * error message: - * "The token parameter must be set" - * - * @dataProvider provideBlockUnblockAction - * @expectedException UsageException - */ - function testBlockingActionWithNoToken( $action ) { - $this->doApiRequest( - array( - 'action' => $action, - 'user' => 'UTApiBlockee', - 'reason' => 'Some reason', - ), - null, - false, - self::$users['sysop']->user - ); - } - - /** - * Just provide the 'block' and 'unblock' action to test both API calls - */ - function provideBlockUnblockAction() { - return array( - array( 'block' ), - array( 'unblock' ), - ); - } -} diff --git a/tests/phpunit/includes/api/ApiEditPageTest.php b/tests/phpunit/includes/api/ApiEditPageTest.php deleted file mode 100644 index 5297d6da..00000000 --- a/tests/phpunit/includes/api/ApiEditPageTest.php +++ /dev/null @@ -1,84 +0,0 @@ -doLogin(); - } - - function testEdit( ) { - $name = 'ApiEditPageTest_testEdit'; - - // -- test new page -------------------------------------------- - $apiResult = $this->doApiRequestWithToken( array( - 'action' => 'edit', - 'title' => $name, - 'text' => 'some text', ) ); - $apiResult = $apiResult[0]; - - # Validate API result data - $this->assertArrayHasKey( 'edit', $apiResult ); - $this->assertArrayHasKey( 'result', $apiResult['edit'] ); - $this->assertEquals( 'Success', $apiResult['edit']['result'] ); - - $this->assertArrayHasKey( 'new', $apiResult['edit'] ); - $this->assertArrayNotHasKey( 'nochange', $apiResult['edit'] ); - - $this->assertArrayHasKey( 'pageid', $apiResult['edit'] ); - - // -- test existing page, no change ---------------------------- - $data = $this->doApiRequestWithToken( array( - 'action' => 'edit', - 'title' => $name, - 'text' => 'some text', ) ); - - $this->assertEquals( 'Success', $data[0]['edit']['result'] ); - - $this->assertArrayNotHasKey( 'new', $data[0]['edit'] ); - $this->assertArrayHasKey( 'nochange', $data[0]['edit'] ); - - // -- test existing page, with change -------------------------- - $data = $this->doApiRequestWithToken( array( - 'action' => 'edit', - 'title' => $name, - 'text' => 'different text' ) ); - - $this->assertEquals( 'Success', $data[0]['edit']['result'] ); - - $this->assertArrayNotHasKey( 'new', $data[0]['edit'] ); - $this->assertArrayNotHasKey( 'nochange', $data[0]['edit'] ); - - $this->assertArrayHasKey( 'oldrevid', $data[0]['edit'] ); - $this->assertArrayHasKey( 'newrevid', $data[0]['edit'] ); - $this->assertNotEquals( - $data[0]['edit']['newrevid'], - $data[0]['edit']['oldrevid'], - "revision id should change after edit" - ); - } - - function testEditAppend() { - $this->markTestIncomplete( "not yet implemented" ); - } - - function testEditSection() { - $this->markTestIncomplete( "not yet implemented" ); - } - - function testUndo() { - $this->markTestIncomplete( "not yet implemented" ); - } - - function testEditNonText() { - $this->markTestIncomplete( "not yet implemented" ); - } -} diff --git a/tests/phpunit/includes/api/ApiOptionsTest.php b/tests/phpunit/includes/api/ApiOptionsTest.php deleted file mode 100644 index 5243fca1..00000000 --- a/tests/phpunit/includes/api/ApiOptionsTest.php +++ /dev/null @@ -1,276 +0,0 @@ - 'success' ); - - function setUp() { - parent::setUp(); - - $this->mUserMock = $this->getMockBuilder( 'User' ) - ->disableOriginalConstructor() - ->getMock(); - - $this->mApiMainMock = $this->getMockBuilder( 'ApiBase' ) - ->disableOriginalConstructor() - ->getMock(); - - // Set up groups - $this->mUserMock->expects( $this->any() ) - ->method( 'getEffectiveGroups' )->will( $this->returnValue( array( '*', 'user')) ); - - // Create a new context - $this->mContext = new DerivativeContext( new RequestContext() ); - $this->mContext->getContext()->setTitle( Title::newFromText( 'Test' ) ); - $this->mContext->setUser( $this->mUserMock ); - - $this->mApiMainMock->expects( $this->any() ) - ->method( 'getContext' ) - ->will( $this->returnValue( $this->mContext ) ); - - $this->mApiMainMock->expects( $this->any() ) - ->method( 'getResult' ) - ->will( $this->returnValue( new ApiResult( $this->mApiMainMock ) ) ); - - - // Empty session - $this->mSession = array(); - - $this->mTested = new ApiOptions( $this->mApiMainMock, 'options' ); - - global $wgHooks; - if ( !isset( $wgHooks['GetPreferences'] ) ) { - $wgHooks['GetPreferences'] = array(); - } - $this->mOldGetPreferencesHooks = $wgHooks['GetPreferences']; - $wgHooks['GetPreferences'][] = array( $this, 'hookGetPreferences' ); - } - - public function tearDown() { - global $wgHooks; - - if ( $this->mOldGetPreferencesHooks !== false ) { - $wgHooks['GetPreferences'] = $this->mOldGetPreferencesHooks; - $this->mOldGetPreferencesHooks = false; - } - - parent::tearDown(); - } - - public function hookGetPreferences( $user, &$preferences ) { - foreach ( array( 'name', 'willBeNull', 'willBeEmpty', 'willBeHappy' ) as $k ) { - $preferences[$k] = array( - 'type' => 'text', - 'section' => 'test', - 'label' => ' ', - ); - } - - return true; - } - - private function getSampleRequest( $custom = array() ) { - $request = array( - 'token' => '123ABC', - 'change' => null, - 'optionname' => null, - 'optionvalue' => null, - ); - return array_merge( $request, $custom ); - } - - private function executeQuery( $request ) { - $this->mContext->setRequest( new FauxRequest( $request, true, $this->mSession ) ); - $this->mTested->execute(); - return $this->mTested->getResult()->getData(); - } - - /** - * @expectedException UsageException - */ - public function testNoToken() { - $request = $this->getSampleRequest( array( 'token' => null ) ); - - $this->executeQuery( $request ); - } - - public function testAnon() { - $this->mUserMock->expects( $this->once() ) - ->method( 'isAnon' ) - ->will( $this->returnValue( true ) ); - - try { - $request = $this->getSampleRequest(); - - $this->executeQuery( $request ); - } catch ( UsageException $e ) { - $this->assertEquals( 'notloggedin', $e->getCodeString() ); - $this->assertEquals( 'Anonymous users cannot change preferences', $e->getMessage() ); - return; - } - $this->fail( "UsageException was not thrown" ); - } - - public function testNoOptionname() { - try { - $request = $this->getSampleRequest( array( 'optionvalue' => '1' ) ); - - $this->executeQuery( $request ); - } catch ( UsageException $e ) { - $this->assertEquals( 'nooptionname', $e->getCodeString() ); - $this->assertEquals( 'The optionname parameter must be set', $e->getMessage() ); - return; - } - $this->fail( "UsageException was not thrown" ); - } - - public function testNoChanges() { - $this->mUserMock->expects( $this->never() ) - ->method( 'resetOptions' ); - - $this->mUserMock->expects( $this->never() ) - ->method( 'setOption' ); - - $this->mUserMock->expects( $this->never() ) - ->method( 'saveSettings' ); - - try { - $request = $this->getSampleRequest(); - - $this->executeQuery( $request ); - } catch ( UsageException $e ) { - $this->assertEquals( 'nochanges', $e->getCodeString() ); - $this->assertEquals( 'No changes were requested', $e->getMessage() ); - return; - } - $this->fail( "UsageException was not thrown" ); - } - - public function testReset() { - $this->mUserMock->expects( $this->once() ) - ->method( 'resetOptions' ); - - $this->mUserMock->expects( $this->never() ) - ->method( 'setOption' ); - - $this->mUserMock->expects( $this->once() ) - ->method( 'saveSettings' ); - - $request = $this->getSampleRequest( array( 'reset' => '' ) ); - - $response = $this->executeQuery( $request ); - - $this->assertEquals( self::$Success, $response ); - } - - public function testOptionWithValue() { - $this->mUserMock->expects( $this->never() ) - ->method( 'resetOptions' ); - - $this->mUserMock->expects( $this->once() ) - ->method( 'setOption' ) - ->with( $this->equalTo( 'name' ), $this->equalTo( 'value' ) ); - - $this->mUserMock->expects( $this->once() ) - ->method( 'saveSettings' ); - - $request = $this->getSampleRequest( array( 'optionname' => 'name', 'optionvalue' => 'value' ) ); - - $response = $this->executeQuery( $request ); - - $this->assertEquals( self::$Success, $response ); - } - - public function testOptionResetValue() { - $this->mUserMock->expects( $this->never() ) - ->method( 'resetOptions' ); - - $this->mUserMock->expects( $this->once() ) - ->method( 'setOption' ) - ->with( $this->equalTo( 'name' ), $this->equalTo( null ) ); - - $this->mUserMock->expects( $this->once() ) - ->method( 'saveSettings' ); - - $request = $this->getSampleRequest( array( 'optionname' => 'name' ) ); - $response = $this->executeQuery( $request ); - - $this->assertEquals( self::$Success, $response ); - } - - public function testChange() { - $this->mUserMock->expects( $this->never() ) - ->method( 'resetOptions' ); - - $this->mUserMock->expects( $this->at( 1 ) ) - ->method( 'getOptions' ); - - $this->mUserMock->expects( $this->at( 2 ) ) - ->method( 'setOption' ) - ->with( $this->equalTo( 'willBeNull' ), $this->equalTo( null ) ); - - $this->mUserMock->expects( $this->at( 3 ) ) - ->method( 'getOptions' ); - - $this->mUserMock->expects( $this->at( 4 ) ) - ->method( 'setOption' ) - ->with( $this->equalTo( 'willBeEmpty' ), $this->equalTo( '' ) ); - - $this->mUserMock->expects( $this->at( 5 ) ) - ->method( 'getOptions' ); - - $this->mUserMock->expects( $this->at( 6 ) ) - ->method( 'setOption' ) - ->with( $this->equalTo( 'willBeHappy' ), $this->equalTo( 'Happy' ) ); - - $this->mUserMock->expects( $this->once() ) - ->method( 'saveSettings' ); - - $request = $this->getSampleRequest( array( 'change' => 'willBeNull|willBeEmpty=|willBeHappy=Happy' ) ); - - $response = $this->executeQuery( $request ); - - $this->assertEquals( self::$Success, $response ); - } - - public function testResetChangeOption() { - $this->mUserMock->expects( $this->once() ) - ->method( 'resetOptions' ); - - $this->mUserMock->expects( $this->at( 2 ) ) - ->method( 'getOptions' ); - - $this->mUserMock->expects( $this->at( 3 ) ) - ->method( 'setOption' ) - ->with( $this->equalTo( 'willBeHappy' ), $this->equalTo( 'Happy' ) ); - - $this->mUserMock->expects( $this->at( 4 ) ) - ->method( 'getOptions' ); - - $this->mUserMock->expects( $this->at( 5 ) ) - ->method( 'setOption' ) - ->with( $this->equalTo( 'name' ), $this->equalTo( 'value' ) ); - - $this->mUserMock->expects( $this->once() ) - ->method( 'saveSettings' ); - - $args = array( - 'reset' => '', - 'change' => 'willBeHappy=Happy', - 'optionname' => 'name', - 'optionvalue' => 'value' - ); - - $response = $this->executeQuery( $this->getSampleRequest( $args ) ); - - $this->assertEquals( self::$Success, $response ); - } -} diff --git a/tests/phpunit/includes/api/ApiPurgeTest.php b/tests/phpunit/includes/api/ApiPurgeTest.php deleted file mode 100644 index 2566c6cd..00000000 --- a/tests/phpunit/includes/api/ApiPurgeTest.php +++ /dev/null @@ -1,40 +0,0 @@ -doLogin(); - } - - /** - * @group Broken - */ - function testPurgeMainPage() { - if ( !Title::newFromText( 'UTPage' )->exists() ) { - $this->markTestIncomplete( "The article [[UTPage]] does not exist" ); - } - - $somePage = mt_rand(); - - $data = $this->doApiRequest( array( - 'action' => 'purge', - 'titles' => 'UTPage|' . $somePage . '|%5D' ) ); - - $this->assertArrayHasKey( 'purge', $data[0], - "Must receive a 'purge' result from API" ); - - $this->assertEquals( 3, count( $data[0]['purge'] ), - "Purge request for three articles should give back three results received: " . var_export( $data[0]['purge'], true ) ); - - $pages = array( 'UTPage' => 'purged', $somePage => 'missing', '%5D' => 'invalid' ); - foreach( $data[0]['purge'] as $v ) { - $this->assertArrayHasKey( $pages[$v['title']], $v ); - } - } - -} diff --git a/tests/phpunit/includes/api/ApiQueryTest.php b/tests/phpunit/includes/api/ApiQueryTest.php deleted file mode 100644 index a4b9dc70..00000000 --- a/tests/phpunit/includes/api/ApiQueryTest.php +++ /dev/null @@ -1,68 +0,0 @@ -doLogin(); - } - - function testTitlesGetNormalized() { - - global $wgMetaNamespace; - - $data = $this->doApiRequest( array( - 'action' => 'query', - 'titles' => 'Project:articleA|article_B' ) ); - - - $this->assertArrayHasKey( 'query', $data[0] ); - $this->assertArrayHasKey( 'normalized', $data[0]['query'] ); - - // Forge a normalized title - $to = Title::newFromText( $wgMetaNamespace.':ArticleA' ); - - $this->assertEquals( - array( - 'from' => 'Project:articleA', - 'to' => $to->getPrefixedText(), - ), - $data[0]['query']['normalized'][0] - ); - - $this->assertEquals( - array( - 'from' => 'article_B', - 'to' => 'Article B' - ), - $data[0]['query']['normalized'][1] - ); - - } - - function testTitlesAreRejectedIfInvalid() { - $title = false; - while( !$title || Title::newFromText( $title )->exists() ) { - $title = md5( mt_rand( 0, 10000 ) + rand( 0, 999000 ) ); - } - - $data = $this->doApiRequest( array( - 'action' => 'query', - 'titles' => $title . '|Talk:' ) ); - - $this->assertArrayHasKey( 'query', $data[0] ); - $this->assertArrayHasKey( 'pages', $data[0]['query'] ); - $this->assertEquals( 2, count( $data[0]['query']['pages'] ) ); - - $this->assertArrayHasKey( -2, $data[0]['query']['pages'] ); - $this->assertArrayHasKey( -1, $data[0]['query']['pages'] ); - - $this->assertArrayHasKey( 'missing', $data[0]['query']['pages'][-2] ); - $this->assertArrayHasKey( 'invalid', $data[0]['query']['pages'][-1] ); - } - -} diff --git a/tests/phpunit/includes/api/ApiTest.php b/tests/phpunit/includes/api/ApiTest.php deleted file mode 100644 index c3eacd5b..00000000 --- a/tests/phpunit/includes/api/ApiTest.php +++ /dev/null @@ -1,280 +0,0 @@ -assertEquals( - null, $mock->requireOnlyOneParameter( array( "filename" => "foo.txt", - "enablechunks" => false ), "filename", "enablechunks" ) ); - } - - /** - * @expectedException UsageException - */ - function testRequireOnlyOneParameterZero() { - $mock = new MockApi(); - - $this->assertEquals( - null, $mock->requireOnlyOneParameter( array( "filename" => "foo.txt", - "enablechunks" => 0 ), "filename", "enablechunks" ) ); - } - - /** - * @expectedException UsageException - */ - function testRequireOnlyOneParameterTrue() { - $mock = new MockApi(); - - $this->assertEquals( - null, $mock->requireOnlyOneParameter( array( "filename" => "foo.txt", - "enablechunks" => true ), "filename", "enablechunks" ) ); - } - - /** - * Test that the API will accept a FauxRequest and execute. The help action - * (default) throws a UsageException. Just validate we're getting proper XML - * - * @expectedException UsageException - */ - function testApi() { - - $api = new ApiMain( - new FauxRequest( array( 'action' => 'help', 'format' => 'xml' ) ) - ); - $api->execute(); - $api->getPrinter()->setBufferResult( true ); - $api->printResult( false ); - $resp = $api->getPrinter()->getBuffer(); - - libxml_use_internal_errors( true ); - $sxe = simplexml_load_string( $resp ); - $this->assertNotInternalType( "bool", $sxe ); - $this->assertThat( $sxe, $this->isInstanceOf( "SimpleXMLElement" ) ); - } - - /** - * Test result of attempted login with an empty username - */ - function testApiLoginNoName() { - $data = $this->doApiRequest( array( 'action' => 'login', - 'lgname' => '', 'lgpassword' => self::$users['sysop']->password, - ) ); - $this->assertEquals( 'NoName', $data[0]['login']['result'] ); - } - - function testApiLoginBadPass() { - global $wgServer; - - $user = self::$users['sysop']; - $user->user->logOut(); - - if ( !isset( $wgServer ) ) { - $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' ); - } - $ret = $this->doApiRequest( array( - "action" => "login", - "lgname" => $user->username, - "lgpassword" => "bad", - ) - ); - - $result = $ret[0]; - - $this->assertNotInternalType( "bool", $result ); - $a = $result["login"]["result"]; - $this->assertEquals( "NeedToken", $a ); - - $token = $result["login"]["token"]; - - $ret = $this->doApiRequest( array( - "action" => "login", - "lgtoken" => $token, - "lgname" => $user->username, - "lgpassword" => "badnowayinhell", - ), $ret[2] - ); - - $result = $ret[0]; - - $this->assertNotInternalType( "bool", $result ); - $a = $result["login"]["result"]; - - $this->assertEquals( "WrongPass", $a ); - } - - function testApiLoginGoodPass() { - global $wgServer; - - if ( !isset( $wgServer ) ) { - $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' ); - } - - $user = self::$users['sysop']; - $user->user->logOut(); - - $ret = $this->doApiRequest( array( - "action" => "login", - "lgname" => $user->username, - "lgpassword" => $user->password, - ) - ); - - $result = $ret[0]; - $this->assertNotInternalType( "bool", $result ); - $this->assertNotInternalType( "null", $result["login"] ); - - $a = $result["login"]["result"]; - $this->assertEquals( "NeedToken", $a ); - $token = $result["login"]["token"]; - - $ret = $this->doApiRequest( array( - "action" => "login", - "lgtoken" => $token, - "lgname" => $user->username, - "lgpassword" => $user->password, - ), $ret[2] - ); - - $result = $ret[0]; - - $this->assertNotInternalType( "bool", $result ); - $a = $result["login"]["result"]; - - $this->assertEquals( "Success", $a ); - } - - /** - * @group Broken - */ - function testApiGotCookie() { - $this->markTestIncomplete( "The server can't do external HTTP requests, and the internal one won't give cookies" ); - - global $wgServer, $wgScriptPath; - - if ( !isset( $wgServer ) ) { - $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' ); - } - $user = self::$users['sysop']; - - $req = MWHttpRequest::factory( self::$apiUrl . "?action=login&format=xml", - array( "method" => "POST", - "postData" => array( - "lgname" => $user->username, - "lgpassword" => $user->password ) ) ); - $req->execute(); - - libxml_use_internal_errors( true ); - $sxe = simplexml_load_string( $req->getContent() ); - $this->assertNotInternalType( "bool", $sxe ); - $this->assertThat( $sxe, $this->isInstanceOf( "SimpleXMLElement" ) ); - $this->assertNotInternalType( "null", $sxe->login[0] ); - - $a = $sxe->login[0]->attributes()->result[0]; - $this->assertEquals( ' result="NeedToken"', $a->asXML() ); - $token = (string)$sxe->login[0]->attributes()->token; - - $req->setData( array( - "lgtoken" => $token, - "lgname" => $user->username, - "lgpassword" => $user->password ) ); - $req->execute(); - - $cj = $req->getCookieJar(); - $serverName = parse_url( $wgServer, PHP_URL_HOST ); - $this->assertNotEquals( false, $serverName ); - $serializedCookie = $cj->serializeToHttpRequest( $wgScriptPath, $serverName ); - $this->assertNotEquals( '', $serializedCookie ); - $this->assertRegexp( '/_session=[^;]*; .*UserID=[0-9]*; .*UserName=' . $user->userName . '; .*Token=/', $serializedCookie ); - - return $cj; - } - - /** - * @todo Finish filling me out...what are we trying to test here? - */ - function testApiListPages() { - global $wgServer; - if ( !isset( $wgServer ) ) { - $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' ); - } - - $ret = $this->doApiRequest( array( - 'action' => 'query', - 'prop' => 'revisions', - 'titles' => 'Main Page', - 'rvprop' => 'timestamp|user|comment|content', - ) ); - - $result = $ret[0]['query']['pages']; - $this->markTestIncomplete( "Somebody needs to finish loving me" ); - } - - function testRunLogin() { - $sysopUser = self::$users['sysop']; - $data = $this->doApiRequest( array( - 'action' => 'login', - 'lgname' => $sysopUser->username, - 'lgpassword' => $sysopUser->password ) ); - - $this->assertArrayHasKey( "login", $data[0] ); - $this->assertArrayHasKey( "result", $data[0]['login'] ); - $this->assertEquals( "NeedToken", $data[0]['login']['result'] ); - $token = $data[0]['login']['token']; - - $data = $this->doApiRequest( array( - 'action' => 'login', - "lgtoken" => $token, - "lgname" => $sysopUser->username, - "lgpassword" => $sysopUser->password ), $data[2] ); - - $this->assertArrayHasKey( "login", $data[0] ); - $this->assertArrayHasKey( "result", $data[0]['login'] ); - $this->assertEquals( "Success", $data[0]['login']['result'] ); - $this->assertArrayHasKey( 'lgtoken', $data[0]['login'] ); - - return $data; - } - - function testGettingToken() { - foreach ( self::$users as $user ) { - $this->runTokenTest( $user ); - } - } - - function runTokenTest( $user ) { - - $data = $this->getTokenList( $user ); - - $this->assertArrayHasKey( 'query', $data[0] ); - $this->assertArrayHasKey( 'pages', $data[0]['query'] ); - $keys = array_keys( $data[0]['query']['pages'] ); - $key = array_pop( $keys ); - - $rights = $user->user->getRights(); - - $this->assertArrayHasKey( $key, $data[0]['query']['pages'] ); - $this->assertArrayHasKey( 'edittoken', $data[0]['query']['pages'][$key] ); - $this->assertArrayHasKey( 'movetoken', $data[0]['query']['pages'][$key] ); - - if ( isset( $rights['delete'] ) ) { - $this->assertArrayHasKey( 'deletetoken', $data[0]['query']['pages'][$key] ); - } - - if ( isset( $rights['block'] ) ) { - $this->assertArrayHasKey( 'blocktoken', $data[0]['query']['pages'][$key] ); - $this->assertArrayHasKey( 'unblocktoken', $data[0]['query']['pages'][$key] ); - } - - if ( isset( $rights['protect'] ) ) { - $this->assertArrayHasKey( 'protecttoken', $data[0]['query']['pages'][$key] ); - } - - return $data; - } -} diff --git a/tests/phpunit/includes/api/ApiTestCase.php b/tests/phpunit/includes/api/ApiTestCase.php deleted file mode 100644 index b84292e3..00000000 --- a/tests/phpunit/includes/api/ApiTestCase.php +++ /dev/null @@ -1,187 +0,0 @@ - new TestUser( - 'Apitestsysop', - 'Api Test Sysop', - 'api_test_sysop@example.com', - array( 'sysop' ) - ), - 'uploader' => new TestUser( - 'Apitestuser', - 'Api Test User', - 'api_test_user@example.com', - array() - ) - ); - - $wgUser = self::$users['sysop']->user; - - $this->apiContext = new ApiTestContext(); - - } - - protected function doApiRequest( Array $params, Array $session = null, $appendModule = false, User $user = null ) { - global $wgRequest, $wgUser; - - if ( is_null( $session ) ) { - # re-use existing global session by default - $session = $wgRequest->getSessionArray(); - } - - # set up global environment - if ( $user ) { - $wgUser = $user; - } - - $wgRequest = new FauxRequest( $params, true, $session ); - RequestContext::getMain()->setRequest( $wgRequest ); - - # set up local environment - $context = $this->apiContext->newTestContext( $wgRequest, $wgUser ); - - $module = new ApiMain( $context, true ); - - # run it! - $module->execute(); - - # construct result - $results = array( - $module->getResultData(), - $context->getRequest(), - $context->getRequest()->getSessionArray() - ); - if( $appendModule ) { - $results[] = $module; - } - - return $results; - } - - /** - * Add an edit token to the API request - * This is cheating a bit -- we grab a token in the correct format and then add it to the pseudo-session and to the - * request, without actually requesting a "real" edit token - * @param $params Array: key-value API params - * @param $session Array|null: session array - * @param $user User|null A User object for the context - */ - protected function doApiRequestWithToken( Array $params, Array $session = null, User $user = null ) { - global $wgRequest; - - if ( $session === null ) { - $session = $wgRequest->getSessionArray(); - } - - if ( $session['wsToken'] ) { - // add edit token to fake session - $session['wsEditToken'] = $session['wsToken']; - // add token to request parameters - $params['token'] = md5( $session['wsToken'] ) . User::EDIT_TOKEN_SUFFIX; - return $this->doApiRequest( $params, $session, false, $user ); - } else { - throw new Exception( "request data not in right format" ); - } - } - - protected function doLogin() { - $data = $this->doApiRequest( array( - 'action' => 'login', - 'lgname' => self::$users['sysop']->username, - 'lgpassword' => self::$users['sysop']->password ) ); - - $token = $data[0]['login']['token']; - - $data = $this->doApiRequest( array( - 'action' => 'login', - 'lgtoken' => $token, - 'lgname' => self::$users['sysop']->username, - 'lgpassword' => self::$users['sysop']->password - ), $data[2] ); - - return $data; - } - - protected function getTokenList( $user, $session = null ) { - $data = $this->doApiRequest( array( - 'action' => 'query', - 'titles' => 'Main Page', - 'intoken' => 'edit|delete|protect|move|block|unblock|watch', - 'prop' => 'info' ), $session, false, $user->user ); - return $data; - } -} - -class UserWrapper { - public $userName, $password, $user; - - public function __construct( $userName, $password, $group = '' ) { - $this->userName = $userName; - $this->password = $password; - - $this->user = User::newFromName( $this->userName ); - if ( !$this->user->getID() ) { - $this->user = User::createNew( $this->userName, array( - "email" => "test@example.com", - "real_name" => "Test User" ) ); - } - $this->user->setPassword( $this->password ); - - if ( $group !== '' ) { - $this->user->addGroup( $group ); - } - $this->user->saveSettings(); - } -} - -class MockApi extends ApiBase { - public function execute() { } - public function getVersion() { } - - public function __construct() { } - - public function getAllowedParams() { - return array( - 'filename' => null, - 'enablechunks' => false, - 'sessionkey' => null, - ); - } -} - -class ApiTestContext extends RequestContext { - - /** - * Returns a DerivativeContext with the request variables in place - * - * @param $request WebRequest request object including parameters and session - * @param $user User or null - * @return DerivativeContext - */ - public function newTestContext( WebRequest $request, User $user = null ) { - $context = new DerivativeContext( $this ); - $context->setRequest( $request ); - if ( $user !== null ) { - $context->setUser( $user ); - } - return $context; - } -} diff --git a/tests/phpunit/includes/api/ApiTestCaseUpload.php b/tests/phpunit/includes/api/ApiTestCaseUpload.php deleted file mode 100644 index 39c79547..00000000 --- a/tests/phpunit/includes/api/ApiTestCaseUpload.php +++ /dev/null @@ -1,148 +0,0 @@ -clearFakeUploads(); - } - - public function tearDown() { - $this->clearTempUpload(); - } - - /** - * Helper function -- remove files and associated articles by Title - * @param $title Title: title to be removed - */ - public function deleteFileByTitle( $title ) { - if ( $title->exists() ) { - $file = wfFindFile( $title, array( 'ignoreRedirect' => true ) ); - $noOldArchive = ""; // yes this really needs to be set this way - $comment = "removing for test"; - $restrictDeletedVersions = false; - $status = FileDeleteForm::doDelete( $title, $file, $noOldArchive, $comment, $restrictDeletedVersions ); - if ( !$status->isGood() ) { - return false; - } - $page = WikiPage::factory( $title ); - $page->doDeleteArticle( "removing for test" ); - - // see if it now doesn't exist; reload - $title = Title::newFromText( $title->getText(), NS_FILE ); - } - return ! ( $title && $title instanceof Title && $title->exists() ); - } - - /** - * Helper function -- remove files and associated articles with a particular filename - * @param $fileName String: filename to be removed - */ - public function deleteFileByFileName( $fileName ) { - return $this->deleteFileByTitle( Title::newFromText( $fileName, NS_FILE ) ); - } - - - /** - * Helper function -- given a file on the filesystem, find matching content in the db (and associated articles) and remove them. - * @param $filePath String: path to file on the filesystem - */ - public function deleteFileByContent( $filePath ) { - $hash = FSFile::getSha1Base36FromPath( $filePath ); - $dupes = RepoGroup::singleton()->findBySha1( $hash ); - $success = true; - foreach ( $dupes as $dupe ) { - $success &= $this->deleteFileByTitle( $dupe->getTitle() ); - } - return $success; - } - - /** - * Fake an upload by dumping the file into temp space, and adding info to $_FILES. - * (This is what PHP would normally do). - * @param $fieldName String: name this would have in the upload form - * @param $fileName String: name to title this - * @param $type String: mime type - * @param $filePath String: path where to find file contents - */ - function fakeUploadFile( $fieldName, $fileName, $type, $filePath ) { - $tmpName = tempnam( wfTempDir(), "" ); - if ( !file_exists( $filePath ) ) { - throw new Exception( "$filePath doesn't exist!" ); - }; - - if ( !copy( $filePath, $tmpName ) ) { - throw new Exception( "couldn't copy $filePath to $tmpName" ); - } - - clearstatcache(); - $size = filesize( $tmpName ); - if ( $size === false ) { - throw new Exception( "couldn't stat $tmpName" ); - } - - $_FILES[ $fieldName ] = array( - 'name' => $fileName, - 'type' => $type, - 'tmp_name' => $tmpName, - 'size' => $size, - 'error' => null - ); - - return true; - - } - function fakeUploadChunk( $fieldName, $fileName, $type, & $chunkData ){ - $tmpName = tempnam( wfTempDir(), "" ); - // copy the chunk data to temp location: - if ( !file_put_contents( $tmpName, $chunkData ) ) { - throw new Exception( "couldn't copy chunk data to $tmpName" ); - } - - clearstatcache(); - $size = filesize( $tmpName ); - if ( $size === false ) { - throw new Exception( "couldn't stat $tmpName" ); - } - - $_FILES[ $fieldName ] = array( - 'name' => $fileName, - 'type' => $type, - 'tmp_name' => $tmpName, - 'size' => $size, - 'error' => null - ); - } - - function clearTempUpload() { - if( isset( $_FILES['file']['tmp_name'] ) ) { - $tmp = $_FILES['file']['tmp_name']; - if( file_exists( $tmp ) ) { - unlink( $tmp ); - } - } - } - - /** - * Remove traces of previous fake uploads - */ - function clearFakeUploads() { - $_FILES = array(); - } - - - - -} diff --git a/tests/phpunit/includes/api/ApiUploadTest.php b/tests/phpunit/includes/api/ApiUploadTest.php deleted file mode 100644 index 642fed05..00000000 --- a/tests/phpunit/includes/api/ApiUploadTest.php +++ /dev/null @@ -1,569 +0,0 @@ - 'login', - 'lgname' => $user->username, - 'lgpassword' => $user->password - ); - list( $result, , $session ) = $this->doApiRequest( $params ); - $this->assertArrayHasKey( "login", $result ); - $this->assertArrayHasKey( "result", $result['login'] ); - $this->assertEquals( "NeedToken", $result['login']['result'] ); - $token = $result['login']['token']; - - $params = array( - 'action' => 'login', - 'lgtoken' => $token, - 'lgname' => $user->username, - 'lgpassword' => $user->password - ); - list( $result, , $session ) = $this->doApiRequest( $params, $session ); - $this->assertArrayHasKey( "login", $result ); - $this->assertArrayHasKey( "result", $result['login'] ); - $this->assertEquals( "Success", $result['login']['result'] ); - $this->assertArrayHasKey( 'lgtoken', $result['login'] ); - - $this->assertNotEmpty( $session, 'API Login must return a session' ); - return $session; - - } - - /** - * @depends testLogin - */ - public function testUploadRequiresToken( $session ) { - $exception = false; - try { - $this->doApiRequest( array( - 'action' => 'upload' - ) ); - } catch ( UsageException $e ) { - $exception = true; - $this->assertEquals( "The token parameter must be set", $e->getMessage() ); - } - $this->assertTrue( $exception, "Got exception" ); - } - - /** - * @depends testLogin - */ - public function testUploadMissingParams( $session ) { - $exception = false; - try { - $this->doApiRequestWithToken( array( - 'action' => 'upload', - ), $session, self::$users['uploader']->user ); - } catch ( UsageException $e ) { - $exception = true; - $this->assertEquals( "One of the parameters filekey, file, url, statuskey is required", - $e->getMessage() ); - } - $this->assertTrue( $exception, "Got exception" ); - } - - - /** - * @depends testLogin - */ - public function testUpload( $session ) { - $extension = 'png'; - $mimeType = 'image/png'; - - try { - $randomImageGenerator = new RandomImageGenerator(); - $filePaths = $randomImageGenerator->writeImages( 1, $extension, wfTempDir() ); - } - catch ( Exception $e ) { - $this->markTestIncomplete( $e->getMessage() ); - } - - $filePath = $filePaths[0]; - $fileSize = filesize( $filePath ); - $fileName = basename( $filePath ); - - $this->deleteFileByFileName( $fileName ); - $this->deleteFileByContent( $filePath ); - - - if (! $this->fakeUploadFile( 'file', $fileName, $mimeType, $filePath ) ) { - $this->markTestIncomplete( "Couldn't upload file!\n" ); - } - - $params = array( - 'action' => 'upload', - 'filename' => $fileName, - 'file' => 'dummy content', - 'comment' => 'dummy comment', - 'text' => "This is the page text for $fileName", - ); - - $exception = false; - try { - list( $result, , ) = $this->doApiRequestWithToken( $params, $session, - self::$users['uploader']->user ); - } catch ( UsageException $e ) { - $exception = true; - } - $this->assertTrue( isset( $result['upload'] ) ); - $this->assertEquals( 'Success', $result['upload']['result'] ); - $this->assertEquals( $fileSize, ( int )$result['upload']['imageinfo']['size'] ); - $this->assertEquals( $mimeType, $result['upload']['imageinfo']['mime'] ); - $this->assertFalse( $exception ); - - // clean up - $this->deleteFileByFilename( $fileName ); - unlink( $filePath ); - } - - - /** - * @depends testLogin - */ - public function testUploadZeroLength( $session ) { - $mimeType = 'image/png'; - - $filePath = tempnam( wfTempDir(), "" ); - $fileName = "apiTestUploadZeroLength.png"; - - $this->deleteFileByFileName( $fileName ); - - if (! $this->fakeUploadFile( 'file', $fileName, $mimeType, $filePath ) ) { - $this->markTestIncomplete( "Couldn't upload file!\n" ); - } - - $params = array( - 'action' => 'upload', - 'filename' => $fileName, - 'file' => 'dummy content', - 'comment' => 'dummy comment', - 'text' => "This is the page text for $fileName", - ); - - $exception = false; - try { - $this->doApiRequestWithToken( $params, $session, self::$users['uploader']->user ); - } catch ( UsageException $e ) { - $this->assertContains( 'The file you submitted was empty', $e->getMessage() ); - $exception = true; - } - $this->assertTrue( $exception ); - - // clean up - $this->deleteFileByFilename( $fileName ); - unlink( $filePath ); - } - - - /** - * @depends testLogin - */ - public function testUploadSameFileName( $session ) { - $extension = 'png'; - $mimeType = 'image/png'; - - try { - $randomImageGenerator = new RandomImageGenerator(); - $filePaths = $randomImageGenerator->writeImages( 2, $extension, wfTempDir() ); - } - catch ( Exception $e ) { - $this->markTestIncomplete( $e->getMessage() ); - } - - // we'll reuse this filename - $fileName = basename( $filePaths[0] ); - - // clear any other files with the same name - $this->deleteFileByFileName( $fileName ); - - // we reuse these params - $params = array( - 'action' => 'upload', - 'filename' => $fileName, - 'file' => 'dummy content', - 'comment' => 'dummy comment', - 'text' => "This is the page text for $fileName", - ); - - // first upload .... should succeed - - if (! $this->fakeUploadFile( 'file', $fileName, $mimeType, $filePaths[0] ) ) { - $this->markTestIncomplete( "Couldn't upload file!\n" ); - } - - $exception = false; - try { - list( $result, , $session ) = $this->doApiRequestWithToken( $params, $session, - self::$users['uploader']->user ); - } catch ( UsageException $e ) { - $exception = true; - } - $this->assertTrue( isset( $result['upload'] ) ); - $this->assertEquals( 'Success', $result['upload']['result'] ); - $this->assertFalse( $exception ); - - // second upload with the same name (but different content) - - if (! $this->fakeUploadFile( 'file', $fileName, $mimeType, $filePaths[1] ) ) { - $this->markTestIncomplete( "Couldn't upload file!\n" ); - } - - $exception = false; - try { - list( $result, , ) = $this->doApiRequestWithToken( $params, $session, - self::$users['uploader']->user ); // FIXME: leaks a temporary file - } catch ( UsageException $e ) { - $exception = true; - } - $this->assertTrue( isset( $result['upload'] ) ); - $this->assertEquals( 'Warning', $result['upload']['result'] ); - $this->assertTrue( isset( $result['upload']['warnings'] ) ); - $this->assertTrue( isset( $result['upload']['warnings']['exists'] ) ); - $this->assertFalse( $exception ); - - // clean up - $this->deleteFileByFilename( $fileName ); - unlink( $filePaths[0] ); - unlink( $filePaths[1] ); - } - - - /** - * @depends testLogin - */ - public function testUploadSameContent( $session ) { - $extension = 'png'; - $mimeType = 'image/png'; - - try { - $randomImageGenerator = new RandomImageGenerator(); - $filePaths = $randomImageGenerator->writeImages( 1, $extension, wfTempDir() ); - } - catch ( Exception $e ) { - $this->markTestIncomplete( $e->getMessage() ); - } - - $fileNames[0] = basename( $filePaths[0] ); - $fileNames[1] = "SameContentAs" . $fileNames[0]; - - // clear any other files with the same name or content - $this->deleteFileByContent( $filePaths[0] ); - $this->deleteFileByFileName( $fileNames[0] ); - $this->deleteFileByFileName( $fileNames[1] ); - - // first upload .... should succeed - - $params = array( - 'action' => 'upload', - 'filename' => $fileNames[0], - 'file' => 'dummy content', - 'comment' => 'dummy comment', - 'text' => "This is the page text for " . $fileNames[0], - ); - - if (! $this->fakeUploadFile( 'file', $fileNames[0], $mimeType, $filePaths[0] ) ) { - $this->markTestIncomplete( "Couldn't upload file!\n" ); - } - - $exception = false; - try { - list( $result, $request, $session ) = $this->doApiRequestWithToken( $params, $session, - self::$users['uploader']->user ); - } catch ( UsageException $e ) { - $exception = true; - } - $this->assertTrue( isset( $result['upload'] ) ); - $this->assertEquals( 'Success', $result['upload']['result'] ); - $this->assertFalse( $exception ); - - - // second upload with the same content (but different name) - - if (! $this->fakeUploadFile( 'file', $fileNames[1], $mimeType, $filePaths[0] ) ) { - $this->markTestIncomplete( "Couldn't upload file!\n" ); - } - - $params = array( - 'action' => 'upload', - 'filename' => $fileNames[1], - 'file' => 'dummy content', - 'comment' => 'dummy comment', - 'text' => "This is the page text for " . $fileNames[1], - ); - - $exception = false; - try { - list( $result, $request, $session ) = $this->doApiRequestWithToken( $params, $session, - self::$users['uploader']->user ); // FIXME: leaks a temporary file - } catch ( UsageException $e ) { - $exception = true; - } - $this->assertTrue( isset( $result['upload'] ) ); - $this->assertEquals( 'Warning', $result['upload']['result'] ); - $this->assertTrue( isset( $result['upload']['warnings'] ) ); - $this->assertTrue( isset( $result['upload']['warnings']['duplicate'] ) ); - $this->assertFalse( $exception ); - - // clean up - $this->deleteFileByFilename( $fileNames[0] ); - $this->deleteFileByFilename( $fileNames[1] ); - unlink( $filePaths[0] ); - } - - - /** - * @depends testLogin - */ - public function testUploadStash( $session ) { - global $wgUser; - $wgUser = self::$users['uploader']->user; // @todo FIXME: still used somewhere - - $extension = 'png'; - $mimeType = 'image/png'; - - try { - $randomImageGenerator = new RandomImageGenerator(); - $filePaths = $randomImageGenerator->writeImages( 1, $extension, wfTempDir() ); - } - catch ( Exception $e ) { - $this->markTestIncomplete( $e->getMessage() ); - } - - $filePath = $filePaths[0]; - $fileSize = filesize( $filePath ); - $fileName = basename( $filePath ); - - $this->deleteFileByFileName( $fileName ); - $this->deleteFileByContent( $filePath ); - - if (! $this->fakeUploadFile( 'file', $fileName, $mimeType, $filePath ) ) { - $this->markTestIncomplete( "Couldn't upload file!\n" ); - } - - $params = array( - 'action' => 'upload', - 'stash' => 1, - 'filename' => $fileName, - 'file' => 'dummy content', - 'comment' => 'dummy comment', - 'text' => "This is the page text for $fileName", - ); - - $exception = false; - try { - list( $result, $request, $session ) = $this->doApiRequestWithToken( $params, $session, - self::$users['uploader']->user ); // FIXME: leaks a temporary file - } catch ( UsageException $e ) { - $exception = true; - } - $this->assertFalse( $exception ); - $this->assertTrue( isset( $result['upload'] ) ); - $this->assertEquals( 'Success', $result['upload']['result'] ); - $this->assertEquals( $fileSize, ( int )$result['upload']['imageinfo']['size'] ); - $this->assertEquals( $mimeType, $result['upload']['imageinfo']['mime'] ); - $this->assertTrue( isset( $result['upload']['filekey'] ) ); - $this->assertEquals( $result['upload']['sessionkey'], $result['upload']['filekey'] ); - $filekey = $result['upload']['filekey']; - - // it should be visible from Special:UploadStash - // XXX ...but how to test this, with a fake WebRequest with the session? - - // now we should try to release the file from stash - $params = array( - 'action' => 'upload', - 'filekey' => $filekey, - 'filename' => $fileName, - 'comment' => 'dummy comment', - 'text' => "This is the page text for $fileName, altered", - ); - - $this->clearFakeUploads(); - $exception = false; - try { - list( $result, $request, $session ) = $this->doApiRequestWithToken( $params, $session, - self::$users['uploader']->user ); - } catch ( UsageException $e ) { - $exception = true; - } - $this->assertTrue( isset( $result['upload'] ) ); - $this->assertEquals( 'Success', $result['upload']['result'] ); - $this->assertFalse( $exception, "No UsageException exception." ); - - // clean up - $this->deleteFileByFilename( $fileName ); - unlink( $filePath ); - } - - - /** - * @depends testLogin - */ - public function testUploadChunks( $session ) { - global $wgUser; - $wgUser = self::$users['uploader']->user; // @todo FIXME: still used somewhere - - $chunkSize = 1048576; - // Download a large image file - // ( using RandomImageGenerator for large files is not stable ) - $mimeType = 'image/jpeg'; - $url = 'http://upload.wikimedia.org/wikipedia/commons/e/ed/Oberaargletscher_from_Oberaar%2C_2010_07.JPG'; - $filePath = wfTempDir() . '/Oberaargletscher_from_Oberaar.jpg'; - try { - // Only download if the file is not avaliable in the temp location: - if( !is_file( $filePath ) ){ - copy($url, $filePath); - } - } - catch ( Exception $e ) { - $this->markTestIncomplete( $e->getMessage() ); - } - - $fileSize = filesize( $filePath ); - $fileName = basename( $filePath ); - - $this->deleteFileByFileName( $fileName ); - $this->deleteFileByContent( $filePath ); - - // Base upload params: - $params = array( - 'action' => 'upload', - 'stash' => 1, - 'filename' => $fileName, - 'filesize' => $fileSize, - 'offset' => 0, - ); - - // Upload chunks - $chunkSessionKey = false; - $resultOffset = 0; - // Open the file: - $handle = @fopen ($filePath, "r"); - if( $handle === false ){ - $this->markTestIncomplete( "could not open file: $filePath" ); - } - while (!feof ($handle)) { - // Get the current chunk - $chunkData = @fread( $handle, $chunkSize ); - - // Upload the current chunk into the $_FILE object: - $this->fakeUploadChunk( 'chunk', 'blob', $mimeType, $chunkData ); - - // Check for chunkSessionKey - if( !$chunkSessionKey ){ - // Upload fist chunk ( and get the session key ) - try { - list( $result, $request, $session ) = $this->doApiRequestWithToken( $params, $session, - self::$users['uploader']->user ); - } catch ( UsageException $e ) { - $this->markTestIncomplete( $e->getMessage() ); - } - // Make sure we got a valid chunk continue: - $this->assertTrue( isset( $result['upload'] ) ); - $this->assertTrue( isset( $result['upload']['filekey'] ) ); - // If we don't get a session key mark test incomplete. - if( ! isset( $result['upload']['filekey'] ) ){ - $this->markTestIncomplete( "no filekey provided" ); - } - $chunkSessionKey = $result['upload']['filekey']; - $this->assertEquals( 'Continue', $result['upload']['result'] ); - // First chunk should have chunkSize == offset - $this->assertEquals( $chunkSize, $result['upload']['offset'] ); - $resultOffset = $result['upload']['offset']; - continue; - } - // Filekey set to chunk session - $params['filekey'] = $chunkSessionKey; - // Update the offset ( always add chunkSize for subquent chunks should be in-sync with $result['upload']['offset'] ) - $params['offset'] += $chunkSize; - // Make sure param offset is insync with resultOffset: - $this->assertEquals( $resultOffset, $params['offset'] ); - // Upload current chunk - try { - list( $result, $request, $session ) = $this->doApiRequestWithToken( $params, $session, - self::$users['uploader']->user ); - } catch ( UsageException $e ) { - $this->markTestIncomplete( $e->getMessage() ); - } - // Make sure we got a valid chunk continue: - $this->assertTrue( isset( $result['upload'] ) ); - $this->assertTrue( isset( $result['upload']['filekey'] ) ); - - // Check if we were on the last chunk: - if( $params['offset'] + $chunkSize >= $fileSize ){ - $this->assertEquals( 'Success', $result['upload']['result'] ); - break; - } else { - $this->assertEquals( 'Continue', $result['upload']['result'] ); - // update $resultOffset - $resultOffset = $result['upload']['offset']; - } - } - fclose ($handle); - - // Check that we got a valid file result: - wfDebug( __METHOD__ . " hohoh filesize {$fileSize} info {$result['upload']['imageinfo']['size']}\n\n"); - $this->assertEquals( $fileSize, $result['upload']['imageinfo']['size'] ); - $this->assertEquals( $mimeType, $result['upload']['imageinfo']['mime'] ); - $this->assertTrue( isset( $result['upload']['filekey'] ) ); - $filekey = $result['upload']['filekey']; - - // Now we should try to release the file from stash - $params = array( - 'action' => 'upload', - 'filekey' => $filekey, - 'filename' => $fileName, - 'comment' => 'dummy comment', - 'text' => "This is the page text for $fileName, altered", - ); - $this->clearFakeUploads(); - $exception = false; - try { - list( $result, $request, $session ) = $this->doApiRequestWithToken( $params, $session, - self::$users['uploader']->user ); - } catch ( UsageException $e ) { - $exception = true; - } - $this->assertTrue( isset( $result['upload'] ) ); - $this->assertEquals( 'Success', $result['upload']['result'] ); - $this->assertFalse( $exception ); - - // clean up - $this->deleteFileByFilename( $fileName ); - // don't remove downloaded temporary file for fast subquent tests. - //unlink( $filePath ); - } -} diff --git a/tests/phpunit/includes/api/ApiWatchTest.php b/tests/phpunit/includes/api/ApiWatchTest.php deleted file mode 100644 index d2e98152..00000000 --- a/tests/phpunit/includes/api/ApiWatchTest.php +++ /dev/null @@ -1,176 +0,0 @@ -doLogin(); - } - - function getTokens() { - $data = $this->getTokenList( self::$users['sysop'] ); - - $keys = array_keys( $data[0]['query']['pages'] ); - $key = array_pop( $keys ); - $pageinfo = $data[0]['query']['pages'][$key]; - - return $pageinfo; - } - - /** - */ - function testWatchEdit() { - $pageinfo = $this->getTokens(); - - $data = $this->doApiRequest( array( - 'action' => 'edit', - 'title' => 'UTPage', - 'text' => 'new text', - 'token' => $pageinfo['edittoken'], - 'watchlist' => 'watch' ) ); - $this->assertArrayHasKey( 'edit', $data[0] ); - $this->assertArrayHasKey( 'result', $data[0]['edit'] ); - $this->assertEquals( 'Success', $data[0]['edit']['result'] ); - - return $data; - } - - /** - * @depends testWatchEdit - */ - function testWatchClear() { - - $pageinfo = $this->getTokens(); - - $data = $this->doApiRequest( array( - 'action' => 'query', - 'list' => 'watchlist' ) ); - - if ( isset( $data[0]['query']['watchlist'] ) ) { - $wl = $data[0]['query']['watchlist']; - - foreach ( $wl as $page ) { - $data = $this->doApiRequest( array( - 'action' => 'watch', - 'title' => $page['title'], - 'unwatch' => true, - 'token' => $pageinfo['watchtoken'] ) ); - } - } - $data = $this->doApiRequest( array( - 'action' => 'query', - 'list' => 'watchlist' ), $data ); - $this->assertArrayHasKey( 'query', $data[0] ); - $this->assertArrayHasKey( 'watchlist', $data[0]['query'] ); - $this->assertEquals( 0, count( $data[0]['query']['watchlist'] ) ); - - return $data; - } - - /** - */ - function testWatchProtect() { - - $pageinfo = $this->getTokens(); - - $data = $this->doApiRequest( array( - 'action' => 'protect', - 'token' => $pageinfo['protecttoken'], - 'title' => 'UTPage', - 'protections' => 'edit=sysop', - 'watchlist' => 'unwatch' ) ); - - $this->assertArrayHasKey( 'protect', $data[0] ); - $this->assertArrayHasKey( 'protections', $data[0]['protect'] ); - $this->assertEquals( 1, count( $data[0]['protect']['protections'] ) ); - $this->assertArrayHasKey( 'edit', $data[0]['protect']['protections'][0] ); - } - - /** - */ - function testGetRollbackToken() { - - $pageinfo = $this->getTokens(); - - if ( !Title::newFromText( 'UTPage' )->exists() ) { - $this->markTestSkipped( "The article [[UTPage]] does not exist" ); //TODO: just create it? - } - - $data = $this->doApiRequest( array( - 'action' => 'query', - 'prop' => 'revisions', - 'titles' => 'UTPage', - 'rvtoken' => 'rollback' ) ); - - $this->assertArrayHasKey( 'query', $data[0] ); - $this->assertArrayHasKey( 'pages', $data[0]['query'] ); - $keys = array_keys( $data[0]['query']['pages'] ); - $key = array_pop( $keys ); - - if ( isset( $data[0]['query']['pages'][$key]['missing'] ) ) { - $this->markTestSkipped( "Target page (UTPage) doesn't exist" ); - } - - $this->assertArrayHasKey( 'pageid', $data[0]['query']['pages'][$key] ); - $this->assertArrayHasKey( 'revisions', $data[0]['query']['pages'][$key] ); - $this->assertArrayHasKey( 0, $data[0]['query']['pages'][$key]['revisions'] ); - $this->assertArrayHasKey( 'rollbacktoken', $data[0]['query']['pages'][$key]['revisions'][0] ); - - return $data; - } - - /** - * @group Broken - * Broken because there is currently no revision info in the $pageinfo - * - * @depends testGetRollbackToken - */ - function testWatchRollback( $data ) { - $keys = array_keys( $data[0]['query']['pages'] ); - $key = array_pop( $keys ); - $pageinfo = $data[0]['query']['pages'][$key]; - $revinfo = $pageinfo['revisions'][0]; - - try { - $data = $this->doApiRequest( array( - 'action' => 'rollback', - 'title' => 'UTPage', - 'user' => $revinfo['user'], - 'token' => $pageinfo['rollbacktoken'], - 'watchlist' => 'watch' ) ); - - $this->assertArrayHasKey( 'rollback', $data[0] ); - $this->assertArrayHasKey( 'title', $data[0]['rollback'] ); - } catch( UsageException $ue ) { - if( $ue->getCodeString() == 'onlyauthor' ) { - $this->markTestIncomplete( "Only one author to 'UTPage', cannot test rollback" ); - } else { - $this->fail( "Received error '" . $ue->getCodeString() . "'" ); - } - } - } - - /** - */ - function testWatchDelete() { - $pageinfo = $this->getTokens(); - - $data = $this->doApiRequest( array( - 'action' => 'delete', - 'token' => $pageinfo['deletetoken'], - 'title' => 'UTPage' ) ); - $this->assertArrayHasKey( 'delete', $data[0] ); - $this->assertArrayHasKey( 'title', $data[0]['delete'] ); - - $data = $this->doApiRequest( array( - 'action' => 'query', - 'list' => 'watchlist' ) ); - - $this->markTestIncomplete( 'This test needs to verify the deleted article was added to the users watchlist' ); - } -} diff --git a/tests/phpunit/includes/api/PrefixUniquenessTest.php b/tests/phpunit/includes/api/PrefixUniquenessTest.php deleted file mode 100644 index 69b01ea7..00000000 --- a/tests/phpunit/includes/api/PrefixUniquenessTest.php +++ /dev/null @@ -1,24 +0,0 @@ -getModules(); - $prefixes = array(); - - foreach ( $modules as $name => $class ) { - $module = new $class( $main, $name ); - $prefix = $module->getModulePrefix(); - if ( isset( $prefixes[$prefix] ) ) { - $this->fail( "Module prefix '{$prefix}' is shared between {$class} and {$prefixes[$prefix]}" ); - } - $prefixes[$module->getModulePrefix()] = $class; - } - $this->assertTrue( true ); // dummy call to make this test non-incomplete - } -} diff --git a/tests/phpunit/includes/api/RandomImageGenerator.php b/tests/phpunit/includes/api/RandomImageGenerator.php deleted file mode 100644 index 8b6a3849..00000000 --- a/tests/phpunit/includes/api/RandomImageGenerator.php +++ /dev/null @@ -1,463 +0,0 @@ - - */ - -/** - * RandomImageGenerator: does what it says on the tin. - * Can fetch a random image, or also write a number of them to disk with random filenames. - */ -class RandomImageGenerator { - - private $dictionaryFile; - private $minWidth = 400 ; - private $maxWidth = 800 ; - private $minHeight = 400 ; - private $maxHeight = 800 ; - private $shapesToDraw = 5 ; - - /** - * Orientations: 0th row, 0th column, EXIF orientation code, rotation 2x2 matrix that is opposite of orientation - * n.b. we do not handle the 'flipped' orientations, which is why there is no entry for 2, 4, 5, or 7. Those - * seem to be rare in real images anyway - * (we also would need a non-symmetric shape for the images to test those, like a letter F) - */ - private static $orientations = array( - array( - '0thRow' => 'top', - '0thCol' => 'left', - 'exifCode' => 1, - 'counterRotation' => array( array( 1, 0 ), array( 0, 1 ) ) - ), - array( - '0thRow' => 'bottom', - '0thCol' => 'right', - 'exifCode' => 3, - 'counterRotation' => array( array( -1, 0 ), array( 0, -1 ) ) - ), - array( - '0thRow' => 'right', - '0thCol' => 'top', - 'exifCode' => 6, - 'counterRotation' => array( array( 0, 1 ), array( 1, 0 ) ) - ), - array( - '0thRow' => 'left', - '0thCol' => 'bottom', - 'exifCode' => 8, - 'counterRotation' => array( array( 0, -1 ), array( -1, 0 ) ) - ) - ); - - - public function __construct( $options = array() ) { - foreach ( array( 'dictionaryFile', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'shapesToDraw' ) as $property ) { - if ( isset( $options[$property] ) ) { - $this->$property = $options[$property]; - } - } - - // find the dictionary file, to generate random names - if ( !isset( $this->dictionaryFile ) ) { - foreach ( array( - '/usr/share/dict/words', - '/usr/dict/words', - __DIR__ . '/words.txt' ) - as $dictionaryFile ) { - if ( is_file( $dictionaryFile ) and is_readable( $dictionaryFile ) ) { - $this->dictionaryFile = $dictionaryFile; - break; - } - } - } - if ( !isset( $this->dictionaryFile ) ) { - throw new Exception( "RandomImageGenerator: dictionary file not found or not specified properly" ); - } - } - - /** - * Writes random images with random filenames to disk in the directory you specify, or current working directory - * - * @param $number Integer: number of filenames to write - * @param $format String: optional, must be understood by ImageMagick, such as 'jpg' or 'gif' - * @param $dir String: directory, optional (will default to current working directory) - * @return Array: filenames we just wrote - */ - function writeImages( $number, $format = 'jpg', $dir = null ) { - $filenames = $this->getRandomFilenames( $number, $format, $dir ); - $imageWriteMethod = $this->getImageWriteMethod( $format ); - foreach( $filenames as $filename ) { - $this->{$imageWriteMethod}( $this->getImageSpec(), $format, $filename ); - } - return $filenames; - } - - - /** - * Figure out how we write images. This is a factor of both format and the local system - * @param $format (a typical extension like 'svg', 'jpg', etc.) - */ - function getImageWriteMethod( $format ) { - global $wgUseImageMagick, $wgImageMagickConvertCommand; - if ( $format === 'svg' ) { - return 'writeSvg'; - } else { - // figure out how to write images - global $wgExiv2Command; - if ( class_exists( 'Imagick' ) && $wgExiv2Command && is_executable( $wgExiv2Command ) ) { - return 'writeImageWithApi'; - } elseif ( $wgUseImageMagick && $wgImageMagickConvertCommand && is_executable( $wgImageMagickConvertCommand ) ) { - return 'writeImageWithCommandLine'; - } - } - throw new Exception( "RandomImageGenerator: could not find a suitable method to write images in '$format' format" ); - } - - /** - * Return a number of randomly-generated filenames - * Each filename uses two words randomly drawn from the dictionary, like elephantine_spatula.jpg - * - * @param $number Integer: of filenames to generate - * @param $extension String: optional, defaults to 'jpg' - * @param $dir String: optional, defaults to current working directory - * @return Array: of filenames - */ - private function getRandomFilenames( $number, $extension = 'jpg', $dir = null ) { - if ( is_null( $dir ) ) { - $dir = getcwd(); - } - $filenames = array(); - foreach( $this->getRandomWordPairs( $number ) as $pair ) { - $basename = $pair[0] . '_' . $pair[1]; - if ( !is_null( $extension ) ) { - $basename .= '.' . $extension; - } - $basename = preg_replace( '/\s+/', '', $basename ); - $filenames[] = "$dir/$basename"; - } - - return $filenames; - - } - - - /** - * Generate data representing an image of random size (within limits), - * consisting of randomly colored and sized upward pointing triangles against a random background color - * (This data is used in the writeImage* methods). - * @return {Mixed} - */ - public function getImageSpec() { - $spec = array(); - - $spec['width'] = mt_rand( $this->minWidth, $this->maxWidth ); - $spec['height'] = mt_rand( $this->minHeight, $this->maxHeight ); - $spec['fill'] = $this->getRandomColor(); - - $diagonalLength = sqrt( pow( $spec['width'], 2 ) + pow( $spec['height'], 2 ) ); - - $draws = array(); - for ( $i = 0; $i <= $this->shapesToDraw; $i++ ) { - $radius = mt_rand( 0, $diagonalLength / 4 ); - if ( $radius == 0 ) { - continue; - } - $originX = mt_rand( -1 * $radius, $spec['width'] + $radius ); - $originY = mt_rand( -1 * $radius, $spec['height'] + $radius ); - $angle = mt_rand( 0, ( 3.141592/2 ) * $radius ) / $radius; - $legDeltaX = round( $radius * sin( $angle ) ); - $legDeltaY = round( $radius * cos( $angle ) ); - - $draw = array(); - $draw['fill'] = $this->getRandomColor(); - $draw['shape'] = array( - array( 'x' => $originX, 'y' => $originY - $radius ), - array( 'x' => $originX + $legDeltaX, 'y' => $originY + $legDeltaY ), - array( 'x' => $originX - $legDeltaX, 'y' => $originY + $legDeltaY ), - array( 'x' => $originX, 'y' => $originY - $radius ) - ); - $draws[] = $draw; - - } - - $spec['draws'] = $draws; - - return $spec; - } - - /** - * Given array( array('x' => 10, 'y' => 20), array( 'x' => 30, y=> 5 ) ) - * returns "10,20 30,5" - * Useful for SVG and imagemagick command line arguments - * @param $shape: Array of arrays, each array containing x & y keys mapped to numeric values - * @return string - */ - static function shapePointsToString( $shape ) { - $points = array(); - foreach ( $shape as $point ) { - $points[] = $point['x'] . ',' . $point['y']; - } - return join( " ", $points ); - } - - /** - * Based on image specification, write a very simple SVG file to disk. - * Ignores the background spec because transparency is cool. :) - * @param $spec: spec describing background and shapes to draw - * @param $format: file format to write (which is obviously always svg here) - * @param $filename: filename to write to - */ - public function writeSvg( $spec, $format, $filename ) { - $svg = new SimpleXmlElement( '' ); - $svg->addAttribute( 'xmlns', 'http://www.w3.org/2000/svg' ); - $svg->addAttribute( 'version', '1.1' ); - $svg->addAttribute( 'width', $spec['width'] ); - $svg->addAttribute( 'height', $spec['height'] ); - $g = $svg->addChild( 'g' ); - foreach ( $spec['draws'] as $drawSpec ) { - $shape = $g->addChild( 'polygon' ); - $shape->addAttribute( 'fill', $drawSpec['fill'] ); - $shape->addAttribute( 'points', self::shapePointsToString( $drawSpec['shape'] ) ); - }; - if ( ! $fh = fopen( $filename, 'w' ) ) { - throw new Exception( "couldn't open $filename for writing" ); - } - fwrite( $fh, $svg->asXML() ); - if ( !fclose($fh) ) { - throw new Exception( "couldn't close $filename" ); - } - } - - /** - * Based on an image specification, write such an image to disk, using Imagick PHP extension - * @param $spec: spec describing background and circles to draw - * @param $format: file format to write - * @param $filename: filename to write to - */ - public function writeImageWithApi( $spec, $format, $filename ) { - // this is a hack because I can't get setImageOrientation() to work. See below. - global $wgExiv2Command; - - $image = new Imagick(); - /** - * If the format is 'jpg', will also add a random orientation -- the image will be drawn rotated with triangle points - * facing in some direction (0, 90, 180 or 270 degrees) and a countering rotation should turn the triangle points upward again - */ - $orientation = self::$orientations[0]; // default is normal orientation - if ( $format == 'jpg' ) { - $orientation = self::$orientations[ array_rand( self::$orientations ) ]; - $spec = self::rotateImageSpec( $spec, $orientation['counterRotation'] ); - } - - $image->newImage( $spec['width'], $spec['height'], new ImagickPixel( $spec['fill'] ) ); - - foreach ( $spec['draws'] as $drawSpec ) { - $draw = new ImagickDraw(); - $draw->setFillColor( $drawSpec['fill'] ); - $draw->polygon( $drawSpec['shape'] ); - $image->drawImage( $draw ); - } - - $image->setImageFormat( $format ); - - // this doesn't work, even though it's documented to do so... - // $image->setImageOrientation( $orientation['exifCode'] ); - - $image->writeImage( $filename ); - - // because the above setImageOrientation call doesn't work... nor can I get an external imagemagick binary to do this either... - // hacking this for now (only works if you have exiv2 installed, a program to read and manipulate exif) - if ( $wgExiv2Command ) { - $cmd = wfEscapeShellArg( $wgExiv2Command ) - . " -M " - . wfEscapeShellArg( "set Exif.Image.Orientation " . $orientation['exifCode'] ) - . " " - . wfEscapeShellArg( $filename ); - - $retval = 0; - $err = wfShellExec( $cmd, $retval ); - if ( $retval !== 0 ) { - print "Error with $cmd: $retval, $err\n"; - } - } - } - - /** - * Given an image specification, produce rotated version - * This is used when simulating a rotated image capture with EXIF orientation - * @param $spec Object returned by getImageSpec - * @param $matrix 2x2 transformation matrix - * @return transformed Spec - */ - private static function rotateImageSpec( &$spec, $matrix ) { - $tSpec = array(); - $dims = self::matrixMultiply2x2( $matrix, $spec['width'], $spec['height'] ); - $correctionX = 0; - $correctionY = 0; - if ( $dims['x'] < 0 ) { - $correctionX = abs( $dims['x'] ); - } - if ( $dims['y'] < 0 ) { - $correctionY = abs( $dims['y'] ); - } - $tSpec['width'] = abs( $dims['x'] ); - $tSpec['height'] = abs( $dims['y'] ); - $tSpec['fill'] = $spec['fill']; - $tSpec['draws'] = array(); - foreach( $spec['draws'] as $draw ) { - $tDraw = array( - 'fill' => $draw['fill'], - 'shape' => array() - ); - foreach( $draw['shape'] as $point ) { - $tPoint = self::matrixMultiply2x2( $matrix, $point['x'], $point['y'] ); - $tPoint['x'] += $correctionX; - $tPoint['y'] += $correctionY; - $tDraw['shape'][] = $tPoint; - } - $tSpec['draws'][] = $tDraw; - } - return $tSpec; - } - - /** - * Given a matrix and a pair of images, return new position - * @param $matrix: 2x2 rotation matrix - * @param $x: x-coordinate number - * @param $y: y-coordinate number - * @return Array transformed with properties x, y - */ - private static function matrixMultiply2x2( $matrix, $x, $y ) { - return array( - 'x' => $x * $matrix[0][0] + $y * $matrix[0][1], - 'y' => $x * $matrix[1][0] + $y * $matrix[1][1] - ); - } - - - /** - * Based on an image specification, write such an image to disk, using the command line ImageMagick program ('convert'). - * - * Sample command line: - * $ convert -size 100x60 xc:rgb(90,87,45) \ - * -draw 'fill rgb(12,34,56) polygon 41,39 44,57 50,57 41,39' \ - * -draw 'fill rgb(99,123,231) circle 59,39 56,57' \ - * -draw 'fill rgb(240,12,32) circle 50,21 50,3' filename.png - * - * @param $spec: spec describing background and shapes to draw - * @param $format: file format to write (unused by this method but kept so it has the same signature as writeImageWithApi) - * @param $filename: filename to write to - */ - public function writeImageWithCommandLine( $spec, $format, $filename ) { - global $wgImageMagickConvertCommand; - $args = array(); - $args[] = "-size " . wfEscapeShellArg( $spec['width'] . 'x' . $spec['height'] ); - $args[] = wfEscapeShellArg( "xc:" . $spec['fill'] ); - foreach( $spec['draws'] as $draw ) { - $fill = $draw['fill']; - $polygon = self::shapePointsToString( $draw['shape'] ); - $drawCommand = "fill $fill polygon $polygon"; - $args[] = '-draw ' . wfEscapeShellArg( $drawCommand ); - } - $args[] = wfEscapeShellArg( $filename ); - - $command = wfEscapeShellArg( $wgImageMagickConvertCommand ) . " " . implode( " ", $args ); - $retval = null; - wfShellExec( $command, $retval ); - return ( $retval === 0 ); - } - - /** - * Generate a string of random colors for ImageMagick or SVG, like "rgb(12, 37, 98)" - * - * @return {String} - */ - public function getRandomColor() { - $components = array(); - for ($i = 0; $i <= 2; $i++ ) { - $components[] = mt_rand( 0, 255 ); - } - return 'rgb(' . join(', ', $components) . ')'; - } - - /** - * Get an array of random pairs of random words, like array( array( 'foo', 'bar' ), array( 'quux', 'baz' ) ); - * - * @param $number Integer: number of pairs - * @return Array: of two-element arrays - */ - private function getRandomWordPairs( $number ) { - $lines = $this->getRandomLines( $number * 2 ); - // construct pairs of words - $pairs = array(); - $count = count( $lines ); - for( $i = 0; $i < $count; $i += 2 ) { - $pairs[] = array( $lines[$i], $lines[$i+1] ); - } - return $pairs; - } - - - /** - * Return N random lines from a file - * - * Will throw exception if the file could not be read or if it had fewer lines than requested. - * - * @param $number_desired Integer: number of lines desired - * @return Array: of exactly n elements, drawn randomly from lines the file - */ - private function getRandomLines( $number_desired ) { - $filepath = $this->dictionaryFile; - - // initialize array of lines - $lines = array(); - for ( $i = 0; $i < $number_desired; $i++ ) { - $lines[] = null; - } - - /* - * This algorithm obtains N random lines from a file in one single pass. It does this by replacing elements of - * a fixed-size array of lines, less and less frequently as it reads the file. - */ - $fh = fopen( $filepath, "r" ); - if ( !$fh ) { - throw new Exception( "couldn't open $filepath" ); - } - $line_number = 0; - $max_index = $number_desired - 1; - while( !feof( $fh ) ) { - $line = fgets( $fh ); - if ( $line !== false ) { - $line_number++; - $line = trim( $line ); - if ( mt_rand( 0, $line_number ) <= $max_index ) { - $lines[ mt_rand( 0, $max_index ) ] = $line; - } - } - } - fclose( $fh ); - if ( $line_number < $number_desired ) { - throw new Exception( "not enough lines in $filepath" ); - } - - return $lines; - } - -} diff --git a/tests/phpunit/includes/api/format/ApiFormatPhpTest.php b/tests/phpunit/includes/api/format/ApiFormatPhpTest.php deleted file mode 100644 index 8209f591..00000000 --- a/tests/phpunit/includes/api/format/ApiFormatPhpTest.php +++ /dev/null @@ -1,19 +0,0 @@ -apiRequest( 'php', array( 'action' => 'query', 'meta' => 'siteinfo' ) ); - - $this->assertInternalType( 'array', unserialize( $data ) ); - $this->assertGreaterThan( 0, count( (array) $data ) ); - - - } - -} diff --git a/tests/phpunit/includes/api/format/ApiFormatTestBase.php b/tests/phpunit/includes/api/format/ApiFormatTestBase.php deleted file mode 100644 index a0b7b020..00000000 --- a/tests/phpunit/includes/api/format/ApiFormatTestBase.php +++ /dev/null @@ -1,22 +0,0 @@ -createPrinterByName( $format ); - $printer->setUnescapeAmps( false ); - - $printer->initPrinter( false ); - - ob_start(); - $printer->execute(); - $out = ob_get_clean(); - - $printer->closePrinter(); - - return $out; - } -} diff --git a/tests/phpunit/includes/api/generateRandomImages.php b/tests/phpunit/includes/api/generateRandomImages.php deleted file mode 100644 index ee345623..00000000 --- a/tests/phpunit/includes/api/generateRandomImages.php +++ /dev/null @@ -1,51 +0,0 @@ -writeImages( $number, $format ); - } -} - -$maintClass = 'GenerateRandomImages'; -require( RUN_MAINTENANCE_IF_MAIN ); - - diff --git a/tests/phpunit/includes/api/words.txt b/tests/phpunit/includes/api/words.txt deleted file mode 100644 index 7ce23ee3..00000000 --- a/tests/phpunit/includes/api/words.txt +++ /dev/null @@ -1,1000 +0,0 @@ -Andaquian -Anoplanthus -Araquaju -Astrophyton -Avarish -Batonga -Bdellidae -Betoyan -Bismarck -Britishness -Carmen -Chatillon -Clement -Coryphaena -Croton -Cyrillianism -Dagomba -Decimus -Dichorisandra -Duculinae -Empusa -Escallonia -Fathometer -Fon -Fundulinae -Gadswoons -Gederathite -Gemini -Gerbera -Gregarinida -Gyracanthus -Halopsychidae -Hasidim -Hemerobius -Ichthyosauridae -Iscariot -Jeames -Jesuitry -Jovian -Judaization -Katie -Ladin -Langhian -Lapithaean -Lisette -Macrochira -Malaxis -Malvastrum -Maranhao -Marxian -Maurist -Metrosideros -Micky -Microsporon -Odacidae -Ophiuchid -Osmorhiza -Paguma -Palesman -Papayaceae -Pastinaca -Philoxenian -Pleurostigma -Rarotongan -Rhodoraceae -Rong -Saho -Sanyakoan -Sardanapalian -Sauropoda -Sedentaria -Shambu -Shukulumbwe -Solonian -Spaniardization -Spirochaetaceae -Stomatopoda -Stratiotes -Taiwanhemp -Titanically -Venetianed -Victrola -Yuman -abatis -abaton -abjoint -acanthoma -acari -acceptance -actinography -acuteness -addiment -adelite -adelomorphic -adelphogamy -adipocele -aelurophobia -affined -aflaunt -agathokakological -aischrolatreia -alarmedly -alebench -aleurone -allelotropic -allerion -alloplastic -allowable -alternacy -alternariose -altricial -ambitionist -amendment -amiableness -amicableness -ammo -amortizable -anchorate -anemometrically -angelocracy -angelological -anodal -anomalure -antedate -antiagglutinin -antirationalist -antiscorbutic -antisplasher -antithesize -antiunionist -antoecian -apolegamic -appropriation -archididascalian -archival -arteriophlebotomy -articulable -asseveration -assignation -atelo -atrienses -atrophy -atterminement -atypic -automower -aveloz -awrist -azteca -bairnteam -balsamweed -bannerman -beardy -becry -beek -beggarwise -bescab -bestness -bethel -bewildering -bibliophilism -bitterblain -blakeberyed -boccarella -bocedization -boobyalla -bourbon -bowbent -bowerbird -brachygnathous -brail -branchiferous -brelaw -brew -brideweed -bridgeable -brombenzamide -buddler -burbankian -burr -buskin -cacochymical -calefactory -caliper -canaliculus -candidature -canellaceous -canniness -canning -cantilene -carbonatation -carthamic -caseum -caudated -causationist -ceruleite -chalder -chalta -charmel -chekan -chillness -chirogymnast -chirpling -chlorinous -cholanthrene -chondroblast -chromatography -chromophilous -chronical -cicatrice -cinchonine -city -clubbing -coastal -coaxially -coercible -coeternity -coff -coinventor -collyba -combinator -complanation -comprehensibility -conchuela -congenital -context -contranatural -corallum -cordately -cornupete -corolliferous -coroneted -corticosterone -coseat -cottage -crocetin -crossleted -crottels -curvedness -cycadeous -cyclism -cylindrically -cynanche -cyrtoceratitic -cystospasm -danceress -dancette -dawny -daydreamy -debar -decarburization -decorousness -decrepitness -delirious -deozonizer -dermatosis -desma -deutencephalic -diacetate -diarthrodial -diathermy -dicolic -dimastigate -dimidiation -dipetto -disavowable -disintrench -disman -dismay -disorder -disoxygenation -dithionous -dogman -dragonfly -dramatical -drawspan -drubbly -drunk -duskly -ecderonic -ectocuniform -ectocyst -ehrwaldite -electrocute -elemicin -embracing -emotionality -enactment -enamor -enclave -endameba -endochylous -endocrinologist -endolymph -endothecal -entasia -epigeous -episcopicide -epitrichial -erminee -erraticalness -eruptivity -erythrocytoschisis -esperance -estuous -eucrystalline -eugeny -evacuant -everbloomer -evocation -exarchateship -exasperate -excorticate -excrementary -exile -expandedly -exponency -expressionist -expulsion -extemporary -extollation -extortive -extrabulbar -extraprostatic -facticide -fairer -fakery -fasibitikite -fatiscent -fearless -febrifuge -ferie -fibrousness -fingered -fisheye -flagpole -flagrantness -fleche -fluidism -folliculin -footbreadth -forceps -forecontrive -forthbring -foveated -fuchsin -fungicidal -funori -gamelang -gametically -garvanzo -gasoliner -gastrophile -germproof -gerontism -gigantical -glaciology -godmotherhood -gooseherd -gordunite -gove -gracilis -greathead -grieveship -guidable -gyromancy -gyrostat -habitus -hailweed -handhole -hangalai -haznadar -heliced -hemihypertrophy -hemimorphic -hemistrumectomy -heptavalent -heptite -herbalist -herpetology -hesperid -hexacarbon -hieromnemon -hobbyless -holodactylic -homoeoarchy -hopperings -hospitable -houseboat -huh -huntedly -hydroponics -hydrosomal -hyperdactylia -hyperperistalsis -hypogeocarpous -ideogram -idiopathical -illegitimate -imambarah -impotently -improvise -impuberal -inaccurately -incarnant -inchoation -incliner -incredulous -indiscriminateness -indulgenced -inebriation -inexpressiveness -infibulate -inflectedness -iniome -ink -inquietly -insaturable -insinuative -instiller -institutive -insultproof -interactionist -intercensal -interpenetrable -intertranspicuous -intrinsicality -inwards -iridiocyte -iridoparalysis -irreportable -isoprene -isosmotic -izard -jacuaru -jaculative -jerkined -joe -joyous -julienne -justicehood -kali -kalidium -katha -kathal -keelage -keratomycosis -khaki -khedival -kinkily -knife -kolo -kraken -kwarta -labba -labber -laboress -lacunar -latch -lauric -lawter -lectotype -leeches -legible -lepidosteoid -leucobasalt -leverer -libellate -limnimeter -lithography -lithotypic -locomotor -logarithmetically -logistician -lyncine -lysogenesis -machan -macromyelon -maharana -mandibulate -manganapatite -marchpane -mas -masochistic -mastaba -matching -meditatively -megalopolitan -melaniline -mentum -mercaptides -mestome -metasomatism -meterless -micronuclear -micropetalous -microreaction -microsporophore -mileway -milliarium -millisecond -misbind -miscollocation -misreader -modernicide -modification -modulant -monkfish -monoamino -monocarbide -monographical -morphinomaniac -mullein -munge -mutilate -mycophagist -myelosarcoma -myospasm -myriadly -nagaika -naphthionate -natant -naviculaeform -nayward -neallotype -necrophilia -nectared -neigher -neogamous -neurodynia -neurorthopteran -nidation -nieceship -nitrobacteria -nitrosification -nogheaded -nonassertive -noneuphonious -nonextant -nonincrease -nonintermittent -nonmetallic -nonprehensile -nonremunerative -nonsocial -nonvesting -noontime -noreaster -nounal -nub -nucleoplasm -nullisome -numero -numerous -oblongatal -observe -obtusilingual -obvert -occipitoatlantal -oceanside -ochlophobist -odontiasis -opalescence -opticon -oraculousness -orarium -organically -orthopedically -ostosis -overadvance -overbuilt -overdiscouragement -overdoer -overhardy -overjocular -overmagnify -overofficered -overpotent -overprizer -overrunner -overshrink -oversimply -oversplash -ovology -oxskin -oxychloride -oxygenant -ozokerite -pactional -palaeoanthropography -palaeographical -palaeopsychology -palliasse -palpebral -pandaric -pantelegraph -papicolist -papulate -parakinetic -parasitism -parochialic -parochialize -passionlike -patch -paucidentate -pawnbrokeress -pecite -pecky -pedipulation -pellitory -perfilograph -periblast -perigemmal -periost -periplus -perishable -periwig -permansive -persistingly -persymmetrical -phantom -phasmatrope -philocaly -philogyny -philosophister -philotherianism -phorology -phototrophic -phrator -phratral -phthisipneumony -physogastry -phytologic -phytoptid -pianograph -picqueter -piculet -pigeoner -pimaric -pinesap -pist -planometer -platano -playful -plea -pleuropneumonic -plowwoman -plump -pluviographical -pneumocele -podophthalmate -polyad -polythalamian -poppyhead -portamento -portmanteau -portraitlike -possible -potassamide -powderer -praepubis -preanesthetic -prebarbaric -predealer -predomination -prefactory -preirrigational -prelector -presbytership -presecure -preservable -prespecialist -preventionism -prewound -princely -priorship -proannexationist -proanthropos -probeable -probouleutic -profitless -proplasma -prosectorial -protecting -protochemistry -protosulphate -pseudoataxia -psilology -psychoneurotic -pterygial -publicist -purgation -purplishness -putatively -pyracene -pyrenomycete -pyromancy -pyrophone -quadroon -quailhead -qualifier -quaternal -rabblelike -rambunctious -rapidness -ratably -rationalism -razor -reannoy -recultivation -regulable -reimplant -reimposition -reimprison -reinjure -reinspiration -reintroduce -remantle -reprehensibility -reptant -require -resteal -restful -returnability -revisableness -rewash -rewhirl -reyield -rhizotomy -rhodamine -rigwiddie -rimester -ripper -rippet -rockish -rockwards -rollicky -roosters -rooted -rosal -rozum -saccharated -sagamore -sagy -salesmanship -salivous -sallet -salta -saprostomous -satiation -sauropsid -sawarra -sawback -scabish -scabrate -scampavia -scientificophilosophical -scirrosity -scoliometer -scolopendrelloid -secantly -seignioral -semibull -semic -seminarianism -semiped -semiprivate -semispherical -semispontaneous -seneschal -septendecimal -serotherapist -servation -sesquisulphuret -severish -sextipartite -sextubercular -shipyard -shuckpen -siderosis -silex -sillyhow -silverbelly -silverbelly -simulacrum -sisham -sixte -skeiner -skiapod -slopped -slubby -smalts -sockmaker -solute -somethingness -somnify -southwester -spathilla -spectrochemical -sphagnology -spinales -spiriting -spirling -spirochetemia -spreadboard -spurflower -squawdom -squeezing -staircase -staker -stamphead -statolith -stekan -stellulate -stinker -stomodaea -streamingly -strikingness -strouthocamelian -stuprum -subacutely -subboreal -subcontractor -subendorsement -subprofitable -subserviate -subsneer -subungual -sucuruju -sugan -sulphocarbolate -summerwood -superficialist -superinference -superregenerative -supplicate -suspendible -synchronizer -syntectic -tachyglossate -tailless -taintment -takingly -taletelling -tarpon -tasteful -taxeater -taxy -teache -teachless -teg -tegmen -teletyper -temperable -ten -tenent -teskere -testes -thallogen -thapsia -thewness -thickety -thiobacteria -thorniness -throwing -thyroprivic -tinnitus -tocalote -tolerationist -tonalamatl -torvous -totality -tottering -toug -tracheopathia -tragedical -translucent -trifoveolate -trilaurin -trophoplasmatic -trunkless -turbanless -turnpiker -twangle -twitterboned -ultraornate -umbilication -unabatingly -unabjured -unadequateness -unaffectedness -unarriving -unassorted -unattacked -unbenumbed -unboasted -unburning -uncensorious -uncongested -uncontemnedly -uncontemporary -uncrook -uncrystallizability -uncurb -uncustomariness -underbillow -undercanopy -underestimation -underhanging -underpetticoated -underpropped -undersole -understocking -underworld -undevout -undisappointing -undistinctive -unfiscal -unfluted -unfreckled -ungentilize -unglobe -unhelped -unhomogeneously -unifoliate -uninflammable -uninterrogated -unisonal -unkindled -unlikeableness -unlisty -unlocked -unmoving -unmultipliable -unnestled -unnoticed -unobservable -unobviated -unoffensively -unofficerlike -unpoetic -unpractically -unquestionableness -unrehearsed -unrevised -unrhetorical -unsadden -unsaluting -unscriptural -unseeking -unshowed -unsolicitous -unsprouted -unsubjective -unsubsidized -unsymbolic -untenant -unterrified -untranquil -untraversed -untrusty -untying -unwillful -unwinding -upspring -uptwist -urachovesical -uropygial -vagabondism -varicoid -varletess -vasal -ventrocaudal -verisimilitude -vermigerous -vibrometer -viminal -virus -vocationalism -voguey -vulnerability -waggle -wamblingly -warmus -waxer -waying -wedgeable -wellmaker -whomever -wigged -witchlike -wokas -woodrowel -woodsman -woolding -xanthelasmic -xiphosternum -yachtman -yachtsmanlike -yelp -zoophytal \ No newline at end of file diff --git a/tests/phpunit/includes/cache/GenderCacheTest.php b/tests/phpunit/includes/cache/GenderCacheTest.php deleted file mode 100644 index a8b987e2..00000000 --- a/tests/phpunit/includes/cache/GenderCacheTest.php +++ /dev/null @@ -1,101 +0,0 @@ -getID() == 0 ) { - $user->addToDatabase(); - $user->setPassword( 'UTMalePassword' ); - } - //ensure the right gender - $user->setOption( 'gender', 'male' ); - $user->saveSettings(); - - $user = User::newFromName( 'UTFemale' ); - if( $user->getID() == 0 ) { - $user->addToDatabase(); - $user->setPassword( 'UTFemalePassword' ); - } - //ensure the right gender - $user->setOption( 'gender', 'female' ); - $user->saveSettings(); - - $user = User::newFromName( 'UTDefaultGender' ); - if( $user->getID() == 0 ) { - $user->addToDatabase(); - $user->setPassword( 'UTDefaultGenderPassword' ); - } - //ensure the default gender - $user->setOption( 'gender', null ); - $user->saveSettings(); - } - - /** - * test usernames - * - * @dataProvider dataUserName - */ - function testUserName( $username, $expectedGender ) { - $genderCache = GenderCache::singleton(); - $gender = $genderCache->getGenderOf( $username ); - $this->assertEquals( $gender, $expectedGender, "GenderCache normal" ); - } - - /** - * genderCache should work with user objects, too - * - * @dataProvider dataUserName - */ - function testUserObjects( $username, $expectedGender ) { - $genderCache = GenderCache::singleton(); - $user = User::newFromName( $username ); - $gender = $genderCache->getGenderOf( $user ); - $this->assertEquals( $gender, $expectedGender, "GenderCache normal" ); - } - - function dataUserName() { - return array( - array( 'UTMale', 'male' ), - array( 'UTFemale', 'female' ), - array( 'UTDefaultGender', 'unknown' ), - array( 'UTNotExist', 'unknown' ), - //some not valid user - array( '127.0.0.1', 'unknown' ), - array( 'user@test', 'unknown' ), - ); - } - - /** - * test strip of subpages to avoid unnecessary queries - * against the never existing username - * - * @dataProvider dataStripSubpages - */ - function testStripSubpages( $pageWithSubpage, $expectedGender ) { - $genderCache = GenderCache::singleton(); - $gender = $genderCache->getGenderOf( $pageWithSubpage ); - $this->assertEquals( $gender, $expectedGender, "GenderCache must strip of subpages" ); - } - - function dataStripSubpages() { - return array( - array( 'UTMale/subpage', 'male' ), - array( 'UTFemale/subpage', 'female' ), - array( 'UTDefaultGender/subpage', 'unknown' ), - array( 'UTNotExist/subpage', 'unknown' ), - array( '127.0.0.1/subpage', 'unknown' ), - ); - } -} diff --git a/tests/phpunit/includes/cache/ProcessCacheLRUTest.php b/tests/phpunit/includes/cache/ProcessCacheLRUTest.php deleted file mode 100644 index 30bfb124..00000000 --- a/tests/phpunit/includes/cache/ProcessCacheLRUTest.php +++ /dev/null @@ -1,239 +0,0 @@ -assertAttributeEquals( array(), 'cache', $cache, $msg ); - } - - /** - * Helper to fill a cache object passed by reference - */ - function fillCache( &$cache, $numEntries ) { - // Fill cache with three values - for( $i=1; $i<=$numEntries; $i++) { - $cache->set( "cache-key-$i", "prop-$i", "value-$i" ); - } - } - - /** - * Generates an array of what would be expected in cache for a given cache - * size and a number of entries filled in sequentially - */ - function getExpectedCache( $cacheMaxEntries, $entryToFill ) { - $expected = array(); - - if( $entryToFill === 0 ) { - # The cache is empty! - return array(); - } elseif( $entryToFill <= $cacheMaxEntries ) { - # Cache is not fully filled - $firstKey = 1; - } else { - # Cache overflowed - $firstKey = 1 + $entryToFill - $cacheMaxEntries; - } - - $lastKey = $entryToFill; - - for( $i=$firstKey; $i<=$lastKey; $i++ ) { - $expected["cache-key-$i"] = array( "prop-$i" => "value-$i" ); - } - return $expected; - } - - /** - * Highlight diff between assertEquals and assertNotSame - */ - function testPhpUnitArrayEquality() { - $one = array( 'A' => 1, 'B' => 2 ); - $two = array( 'B' => 2, 'A' => 1 ); - $this->assertEquals( $one, $two ); // == - $this->assertNotSame( $one, $two ); // === - } - - /** - * @dataProvider provideInvalidConstructorArg - * @expectedException MWException - */ - function testConstructorGivenInvalidValue( $maxSize ) { - $c = new ProcessCacheLRUTestable( $maxSize ); - } - - /** - * Value which are forbidden by the constructor - */ - function provideInvalidConstructorArg() { - return array( - array( null ), - array( array() ), - array( new stdClass() ), - array( 0 ), - array( '5' ), - array( -1 ), - ); - } - - function testAddAndGetAKey() { - $oneCache = new ProcessCacheLRUTestable( 1 ); - $this->assertCacheEmpty( $oneCache ); - - // First set just one value - $oneCache->set( 'cache-key', 'prop1', 'value1' ); - $this->assertEquals( 1, $oneCache->getEntriesCount() ); - $this->assertTrue( $oneCache->has( 'cache-key', 'prop1' ) ); - $this->assertEquals( 'value1', $oneCache->get( 'cache-key', 'prop1' ) ); - } - - function testDeleteOldKey() { - $oneCache = new ProcessCacheLRUTestable( 1 ); - $this->assertCacheEmpty( $oneCache ); - - $oneCache->set( 'cache-key', 'prop1', 'value1' ); - $oneCache->set( 'cache-key', 'prop1', 'value2' ); - $this->assertEquals( 'value2', $oneCache->get( 'cache-key', 'prop1' ) ); - } - - /** - * This test that we properly overflow when filling a cache with - * a sequence of always different cache-keys. Meant to verify we correclty - * delete the older key. - * - * @dataProvider provideCacheFilling - * @param $cacheMaxEntries Maximum entry the created cache will hold - * @param $entryToFill Number of entries to insert in the created cache. - */ - function testFillingCache( $cacheMaxEntries, $entryToFill, $msg = '' ) { - $cache = new ProcessCacheLRUTestable( $cacheMaxEntries ); - $this->fillCache( $cache, $entryToFill); - - $this->assertSame( - $this->getExpectedCache( $cacheMaxEntries, $entryToFill ), - $cache->getCache(), - "Filling a $cacheMaxEntries entries cache with $entryToFill entries" - ); - - } - - /** - * Provider for testFillingCache - */ - function provideCacheFilling() { - // ($cacheMaxEntries, $entryToFill, $msg='') - return array( - array( 1, 0 ), - array( 1, 1 ), - array( 1, 2 ), # overflow - array( 5, 33 ), # overflow - ); - - } - - /** - * Create a cache with only one remaining entry then update - * the first inserted entry. Should bump it to the top. - */ - function testReplaceExistingKeyShouldBumpEntryToTop() { - $maxEntries = 3; - - $cache = new ProcessCacheLRUTestable( $maxEntries ); - // Fill cache leaving just one remaining slot - $this->fillCache( $cache, $maxEntries - 1 ); - - // Set an existing cache key - $cache->set( "cache-key-1", "prop-1", "new-value-for-1" ); - - $this->assertSame( - array( - 'cache-key-2' => array( 'prop-2' => 'value-2' ), - 'cache-key-1' => array( 'prop-1' => 'new-value-for-1' ), - ), - $cache->getCache() - ); - } - - function testRecentlyAccessedKeyStickIn() { - $cache = new ProcessCacheLRUTestable( 2 ); - $cache->set( 'first' , 'prop1', 'value1' ); - $cache->set( 'second', 'prop2', 'value2' ); - - // Get first - $cache->get( 'first', 'prop1' ); - // Cache a third value, should invalidate the least used one - $cache->set( 'third', 'prop3', 'value3' ); - - $this->assertFalse( $cache->has( 'second', 'prop2' ) ); - } - - /** - * This first create a full cache then update the value for the 2nd - * filled entry. - * Given a cache having 1,2,3 as key, updating 2 should bump 2 to - * the top of the queue with the new value: 1,3,2* (* = updated). - */ - function testReplaceExistingKeyInAFullCacheShouldBumpToTop() { - $maxEntries = 3; - - $cache = new ProcessCacheLRUTestable( $maxEntries ); - $this->fillCache( $cache, $maxEntries ); - - // Set an existing cache key - $cache->set( "cache-key-2", "prop-2", "new-value-for-2" ); - $this->assertSame( - array( - 'cache-key-1' => array( 'prop-1' => 'value-1' ), - 'cache-key-3' => array( 'prop-3' => 'value-3' ), - 'cache-key-2' => array( 'prop-2' => 'new-value-for-2' ), - ), - $cache->getCache() - ); - $this->assertEquals( 'new-value-for-2', - $cache->get( 'cache-key-2', 'prop-2' ) - ); - } - - function testBumpExistingKeyToTop() { - $cache = new ProcessCacheLRUTestable( 3 ); - $this->fillCache( $cache, 3 ); - - // Set the very first cache key to a new value - $cache->set( "cache-key-1", "prop-1", "new value for 1" ); - $this->assertEquals( - array( - 'cache-key-2' => array( 'prop-2' => 'value-2' ), - 'cache-key-3' => array( 'prop-3' => 'value-3' ), - 'cache-key-1' => array( 'prop-1' => 'new value for 1' ), - ), - $cache->getCache() - ); - - } - -} - -/** - * Overrides some ProcessCacheLRU methods and properties accessibility. - */ -class ProcessCacheLRUTestable extends ProcessCacheLRU { - public $cache = array(); - - public function getCache() { - return $this->cache; - } - public function getEntriesCount() { - return count( $this->cache ); - } -} diff --git a/tests/phpunit/includes/db/DatabaseSQLTest.php b/tests/phpunit/includes/db/DatabaseSQLTest.php deleted file mode 100644 index e37cd445..00000000 --- a/tests/phpunit/includes/db/DatabaseSQLTest.php +++ /dev/null @@ -1,147 +0,0 @@ -db->getType() !== 'mysql' ) { - $this->markTestSkipped( 'No mysql database' ); - } - } - - /** - * @dataProvider dataSelectSQLText - */ - function testSelectSQLText( $sql, $sqlText ) { - $this->assertEquals( trim( $this->db->selectSQLText( - isset( $sql['tables'] ) ? $sql['tables'] : array(), - isset( $sql['fields'] ) ? $sql['fields'] : array(), - isset( $sql['conds'] ) ? $sql['conds'] : array(), - __METHOD__, - isset( $sql['options'] ) ? $sql['options'] : array(), - isset( $sql['join_conds'] ) ? $sql['join_conds'] : array() - ) ), $sqlText ); - } - - function dataSelectSQLText() { - return array( - array( - array( - 'tables' => 'table', - 'fields' => array( 'field', 'alias' => 'field2' ), - 'conds' => array( 'alias' => 'text' ), - ), - "SELECT field,field2 AS alias " . - "FROM `unittest_table` " . - "WHERE alias = 'text'" - ), - array( - array( - 'tables' => 'table', - 'fields' => array( 'field', 'alias' => 'field2' ), - 'conds' => array( 'alias' => 'text' ), - 'options' => array( 'LIMIT' => 1, 'ORDER BY' => 'field' ), - ), - "SELECT field,field2 AS alias " . - "FROM `unittest_table` " . - "WHERE alias = 'text' " . - "ORDER BY field " . - "LIMIT 1" - ), - array( - array( - 'tables' => array( 'table', 't2' => 'table2' ), - 'fields' => array( 'tid', 'field', 'alias' => 'field2', 't2.id' ), - 'conds' => array( 'alias' => 'text' ), - 'options' => array( 'LIMIT' => 1, 'ORDER BY' => 'field' ), - 'join_conds' => array( 't2' => array( - 'LEFT JOIN', 'tid = t2.id' - )), - ), - "SELECT tid,field,field2 AS alias,t2.id " . - "FROM `unittest_table` LEFT JOIN `unittest_table2` `t2` ON ((tid = t2.id)) " . - "WHERE alias = 'text' " . - "ORDER BY field " . - "LIMIT 1" - ), - array( - array( - 'tables' => array( 'table', 't2' => 'table2' ), - 'fields' => array( 'tid', 'field', 'alias' => 'field2', 't2.id' ), - 'conds' => array( 'alias' => 'text' ), - 'options' => array( 'LIMIT' => 1, 'GROUP BY' => 'field', 'HAVING' => 'COUNT(*) > 1' ), - 'join_conds' => array( 't2' => array( - 'LEFT JOIN', 'tid = t2.id' - )), - ), - "SELECT tid,field,field2 AS alias,t2.id " . - "FROM `unittest_table` LEFT JOIN `unittest_table2` `t2` ON ((tid = t2.id)) " . - "WHERE alias = 'text' " . - "GROUP BY field HAVING COUNT(*) > 1 " . - "LIMIT 1" - ), - array( - array( - 'tables' => array( 'table', 't2' => 'table2' ), - 'fields' => array( 'tid', 'field', 'alias' => 'field2', 't2.id' ), - 'conds' => array( 'alias' => 'text' ), - 'options' => array( 'LIMIT' => 1, 'GROUP BY' => array( 'field', 'field2' ), 'HAVING' => array( 'COUNT(*) > 1', 'field' => 1 ) ), - 'join_conds' => array( 't2' => array( - 'LEFT JOIN', 'tid = t2.id' - )), - ), - "SELECT tid,field,field2 AS alias,t2.id " . - "FROM `unittest_table` LEFT JOIN `unittest_table2` `t2` ON ((tid = t2.id)) " . - "WHERE alias = 'text' " . - "GROUP BY field,field2 HAVING (COUNT(*) > 1) AND field = '1' " . - "LIMIT 1" - ), - ); - } - - /** - * @dataProvider dataConditional - */ - function testConditional( $sql, $sqlText ) { - $this->assertEquals( trim( $this->db->conditional( - $sql['conds'], - $sql['true'], - $sql['false'] - ) ), $sqlText ); - } - - function dataConditional() { - return array( - array( - array( - 'conds' => array( 'field' => 'text' ), - 'true' => 1, - 'false' => 'NULL', - ), - "(CASE WHEN field = 'text' THEN 1 ELSE NULL END)" - ), - array( - array( - 'conds' => array( 'field' => 'text', 'field2' => 'anothertext' ), - 'true' => 1, - 'false' => 'NULL', - ), - "(CASE WHEN field = 'text' AND field2 = 'anothertext' THEN 1 ELSE NULL END)" - ), - array( - array( - 'conds' => 'field=1', - 'true' => 1, - 'false' => 'NULL', - ), - "(CASE WHEN field=1 THEN 1 ELSE NULL END)" - ), - ); - } -} \ No newline at end of file diff --git a/tests/phpunit/includes/db/DatabaseSqliteTest.php b/tests/phpunit/includes/db/DatabaseSqliteTest.php deleted file mode 100644 index d226598b..00000000 --- a/tests/phpunit/includes/db/DatabaseSqliteTest.php +++ /dev/null @@ -1,326 +0,0 @@ -lastQuery = $sql; - return true; - } - - function replaceVars( $s ) { - return parent::replaceVars( $s ); - } -} - -/** - * @group sqlite - * @group Database - */ -class DatabaseSqliteTest extends MediaWikiTestCase { - var $db; - - public function setUp() { - if ( !Sqlite::isPresent() ) { - $this->markTestSkipped( 'No SQLite support detected' ); - } - $this->db = new MockDatabaseSqlite(); - if ( version_compare( $this->db->getServerVersion(), '3.6.0', '<' ) ) { - $this->markTestSkipped( "SQLite at least 3.6 required, {$this->db->getServerVersion()} found" ); - } - } - - private function replaceVars( $sql ) { - // normalize spacing to hide implementation details - return preg_replace( '/\s+/', ' ', $this->db->replaceVars( $sql ) ); - } - - private function assertResultIs( $expected, $res ) { - $this->assertNotNull( $res ); - $i = 0; - foreach( $res as $row ) { - foreach( $expected[$i] as $key => $value ) { - $this->assertTrue( isset( $row->$key ) ); - $this->assertEquals( $value, $row->$key ); - } - $i++; - } - $this->assertEquals( count( $expected ), $i, 'Unexpected number of rows' ); - } - - public function testReplaceVars() { - $this->assertEquals( 'foo', $this->replaceVars( 'foo' ), "Don't break anything accidentally" ); - - $this->assertEquals( "CREATE TABLE /**/foo (foo_key INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " - . "foo_bar TEXT, foo_name TEXT NOT NULL DEFAULT '', foo_int INTEGER, foo_int2 INTEGER );", - $this->replaceVars( "CREATE TABLE /**/foo (foo_key int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, - foo_bar char(13), foo_name varchar(255) binary NOT NULL DEFAULT '', foo_int tinyint ( 8 ), foo_int2 int(16) ) ENGINE=MyISAM;" ) - ); - - $this->assertEquals( "CREATE TABLE foo ( foo1 REAL, foo2 REAL, foo3 REAL );", - $this->replaceVars( "CREATE TABLE foo ( foo1 FLOAT, foo2 DOUBLE( 1,10), foo3 DOUBLE PRECISION );" ) - ); - - $this->assertEquals( "CREATE TABLE foo ( foo_binary1 BLOB, foo_binary2 BLOB );", - $this->replaceVars( "CREATE TABLE foo ( foo_binary1 binary(16), foo_binary2 varbinary(32) );" ) - ); - - $this->assertEquals( "CREATE TABLE text ( text_foo TEXT );", - $this->replaceVars( "CREATE TABLE text ( text_foo tinytext );" ), - 'Table name changed' - ); - - $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );", - $this->replaceVars("CREATE TABLE foo ( foobar INT PRIMARY KEY NOT NULL AUTO_INCREMENT );" ) - ); - $this->assertEquals( "CREATE TABLE foo ( foobar INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL );", - $this->replaceVars("CREATE TABLE foo ( foobar INT PRIMARY KEY AUTO_INCREMENT NOT NULL );" ) - ); - - $this->assertEquals( "CREATE TABLE enums( enum1 TEXT, myenum TEXT)", - $this->replaceVars( "CREATE TABLE enums( enum1 ENUM('A', 'B'), myenum ENUM ('X', 'Y'))" ) - ); - - $this->assertEquals( "ALTER TABLE foo ADD COLUMN foo_bar INTEGER DEFAULT 42", - $this->replaceVars( "ALTER TABLE foo\nADD COLUMN foo_bar int(10) unsigned DEFAULT 42" ) - ); - } - - public function testTableName() { - // @todo Moar! - $db = new DatabaseSqliteStandalone( ':memory:' ); - $this->assertEquals( 'foo', $db->tableName( 'foo' ) ); - $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) ); - $db->tablePrefix( 'foo' ); - $this->assertEquals( 'sqlite_master', $db->tableName( 'sqlite_master' ) ); - $this->assertEquals( 'foobar', $db->tableName( 'bar' ) ); - } - - public function testDuplicateTableStructure() { - $db = new DatabaseSqliteStandalone( ':memory:' ); - $db->query( 'CREATE TABLE foo(foo, barfoo)' ); - - $db->duplicateTableStructure( 'foo', 'bar' ); - $this->assertEquals( 'CREATE TABLE "bar"(foo, barfoo)', - $db->selectField( 'sqlite_master', 'sql', array( 'name' => 'bar' ) ), - 'Normal table duplication' - ); - - $db->duplicateTableStructure( 'foo', 'baz', true ); - $this->assertEquals( 'CREATE TABLE "baz"(foo, barfoo)', - $db->selectField( 'sqlite_temp_master', 'sql', array( 'name' => 'baz' ) ), - 'Creation of temporary duplicate' - ); - $this->assertEquals( 0, - $db->selectField( 'sqlite_master', 'COUNT(*)', array( 'name' => 'baz' ) ), - 'Create a temporary duplicate only' - ); - } - - public function testDuplicateTableStructureVirtual() { - $db = new DatabaseSqliteStandalone( ':memory:' ); - if ( $db->getFulltextSearchModule() != 'FTS3' ) { - $this->markTestSkipped( 'FTS3 not supported, cannot create virtual tables' ); - } - $db->query( 'CREATE VIRTUAL TABLE "foo" USING FTS3(foobar)' ); - - $db->duplicateTableStructure( 'foo', 'bar' ); - $this->assertEquals( 'CREATE VIRTUAL TABLE "bar" USING FTS3(foobar)', - $db->selectField( 'sqlite_master', 'sql', array( 'name' => 'bar' ) ), - 'Duplication of virtual tables' - ); - - $db->duplicateTableStructure( 'foo', 'baz', true ); - $this->assertEquals( 'CREATE VIRTUAL TABLE "baz" USING FTS3(foobar)', - $db->selectField( 'sqlite_master', 'sql', array( 'name' => 'baz' ) ), - "Can't create temporary virtual tables, should fall back to non-temporary duplication" - ); - } - - public function testDeleteJoin() { - $db = new DatabaseSqliteStandalone( ':memory:' ); - $db->query( 'CREATE TABLE a (a_1)', __METHOD__ ); - $db->query( 'CREATE TABLE b (b_1, b_2)', __METHOD__ ); - $db->insert( 'a', array( - array( 'a_1' => 1 ), - array( 'a_1' => 2 ), - array( 'a_1' => 3 ), - ), - __METHOD__ - ); - $db->insert( 'b', array( - array( 'b_1' => 2, 'b_2' => 'a' ), - array( 'b_1' => 3, 'b_2' => 'b' ), - ), - __METHOD__ - ); - $db->deleteJoin( 'a', 'b', 'a_1', 'b_1', array( 'b_2' => 'a' ), __METHOD__ ); - $res = $db->query( "SELECT * FROM a", __METHOD__ ); - $this->assertResultIs( array( - array( 'a_1' => 1 ), - array( 'a_1' => 3 ), - ), - $res - ); - } - - public function testEntireSchema() { - global $IP; - - $result = Sqlite::checkSqlSyntax( "$IP/maintenance/tables.sql" ); - if ( $result !== true ) { - $this->fail( $result ); - } - $this->assertTrue( true ); // avoid test being marked as incomplete due to lack of assertions - } - - /** - * Runs upgrades of older databases and compares results with current schema - * @todo: currently only checks list of tables - */ - public function testUpgrades() { - global $IP, $wgVersion; - - // Versions tested - $versions = array( - //'1.13', disabled for now, was totally screwed up - // SQLite wasn't included in 1.14 - '1.15', - '1.16', - '1.17', - '1.18', - ); - - // Mismatches for these columns we can safely ignore - $ignoredColumns = array( - 'user_newtalk.user_last_timestamp', // r84185 - ); - - $currentDB = new DatabaseSqliteStandalone( ':memory:' ); - $currentDB->sourceFile( "$IP/maintenance/tables.sql" ); - $currentTables = $this->getTables( $currentDB ); - sort( $currentTables ); - - foreach ( $versions as $version ) { - $versions = "upgrading from $version to $wgVersion"; - $db = $this->prepareDB( $version ); - $tables = $this->getTables( $db ); - $this->assertEquals( $currentTables, $tables, "Different tables $versions" ); - foreach ( $tables as $table ) { - $currentCols = $this->getColumns( $currentDB, $table ); - $cols = $this->getColumns( $db, $table ); - $this->assertEquals( - array_keys( $currentCols ), - array_keys( $cols ), - "Mismatching columns for table \"$table\" $versions" - ); - foreach ( $currentCols as $name => $column ) { - $fullName = "$table.$name"; - $this->assertEquals( - (bool)$column->pk, - (bool)$cols[$name]->pk, - "PRIMARY KEY status does not match for column $fullName $versions" - ); - if ( !in_array( $fullName, $ignoredColumns ) ) { - $this->assertEquals( - (bool)$column->notnull, - (bool)$cols[$name]->notnull, - "NOT NULL status does not match for column $fullName $versions" - ); - $this->assertEquals( - $column->dflt_value, - $cols[$name]->dflt_value, - "Default values does not match for column $fullName $versions" - ); - } - } - $currentIndexes = $this->getIndexes( $currentDB, $table ); - $indexes = $this->getIndexes( $db, $table ); - $this->assertEquals( - array_keys( $currentIndexes ), - array_keys( $indexes ), - "mismatching indexes for table \"$table\" $versions" - ); - } - $db->close(); - } - } - - public function testInsertIdType() { - $db = new DatabaseSqliteStandalone( ':memory:' ); - $this->assertInstanceOf( 'ResultWrapper', - $db->query( 'CREATE TABLE a ( a_1 )', __METHOD__ ), "Database creationg" ); - $this->assertTrue( $db->insert( 'a', array( 'a_1' => 10 ), __METHOD__ ), - "Insertion worked" ); - $this->assertEquals( "integer", gettype( $db->insertId() ), "Actual typecheck" ); - $this->assertTrue( $db->close(), "closing database" ); - } - - private function prepareDB( $version ) { - static $maint = null; - if ( $maint === null ) { - $maint = new FakeMaintenance(); - $maint->loadParamsAndArgs( null, array( 'quiet' => 1 ) ); - } - - global $IP; - $db = new DatabaseSqliteStandalone( ':memory:' ); - $db->sourceFile( "$IP/tests/phpunit/data/db/sqlite/tables-$version.sql" ); - $updater = DatabaseUpdater::newForDB( $db, false, $maint ); - $updater->doUpdates( array( 'core' ) ); - return $db; - } - - private function getTables( $db ) { - $list = array_flip( $db->listTables() ); - $excluded = array( - 'math', // moved out of core in 1.18 - 'trackbacks', // removed from core in 1.19 - 'searchindex', - 'searchindex_content', - 'searchindex_segments', - 'searchindex_segdir', - // FTS4 ready!!1 - 'searchindex_docsize', - 'searchindex_stat', - ); - foreach ( $excluded as $t ) { - unset( $list[$t] ); - } - $list = array_flip( $list ); - sort( $list ); - return $list; - } - - private function getColumns( $db, $table ) { - $cols = array(); - $res = $db->query( "PRAGMA table_info($table)" ); - $this->assertNotNull( $res ); - foreach ( $res as $col ) { - $cols[$col->name] = $col; - } - ksort( $cols ); - return $cols; - } - - private function getIndexes( $db, $table ) { - $indexes = array(); - $res = $db->query( "PRAGMA index_list($table)" ); - $this->assertNotNull( $res ); - foreach ( $res as $index ) { - $res2 = $db->query( "PRAGMA index_info({$index->name})" ); - $this->assertNotNull( $res2 ); - $index->columns = array(); - foreach ( $res2 as $col ) { - $index->columns[] = $col; - } - $indexes[$index->name] = $index; - } - ksort( $indexes ); - return $indexes; - } -} diff --git a/tests/phpunit/includes/db/DatabaseTest.php b/tests/phpunit/includes/db/DatabaseTest.php deleted file mode 100644 index 379ffb17..00000000 --- a/tests/phpunit/includes/db/DatabaseTest.php +++ /dev/null @@ -1,215 +0,0 @@ -db = wfGetDB( DB_MASTER ); - } - - function tearDown() { - if ( $this->functionTest ) { - $this->dropFunctions(); - $this->functionTest = false; - } - } - - function testAddQuotesNull() { - $check = "NULL"; - if ( $this->db->getType() === 'sqlite' || $this->db->getType() === 'oracle' ) { - $check = "''"; - } - $this->assertEquals( $check, $this->db->addQuotes( null ) ); - } - - function testAddQuotesInt() { - # returning just "1234" should be ok too, though... - # maybe - $this->assertEquals( - "'1234'", - $this->db->addQuotes( 1234 ) ); - } - - function testAddQuotesFloat() { - # returning just "1234.5678" would be ok too, though - $this->assertEquals( - "'1234.5678'", - $this->db->addQuotes( 1234.5678 ) ); - } - - function testAddQuotesString() { - $this->assertEquals( - "'string'", - $this->db->addQuotes( 'string' ) ); - } - - function testAddQuotesStringQuote() { - $check = "'string''s cause trouble'"; - if ( $this->db->getType() === 'mysql' ) { - $check = "'string\'s cause trouble'"; - } - $this->assertEquals( - $check, - $this->db->addQuotes( "string's cause trouble" ) ); - } - - private function getSharedTableName( $table, $database, $prefix, $format = 'quoted' ) { - global $wgSharedDB, $wgSharedTables, $wgSharedPrefix; - - $oldName = $wgSharedDB; - $oldTables = $wgSharedTables; - $oldPrefix = $wgSharedPrefix; - - $wgSharedDB = $database; - $wgSharedTables = array( $table ); - $wgSharedPrefix = $prefix; - - $ret = $this->db->tableName( $table, $format ); - - $wgSharedDB = $oldName; - $wgSharedTables = $oldTables; - $wgSharedPrefix = $oldPrefix; - - return $ret; - } - - private function prefixAndQuote( $table, $database = null, $prefix = null, $format = 'quoted' ) { - if ( $this->db->getType() === 'sqlite' || $format !== 'quoted' ) { - $quote = ''; - } elseif ( $this->db->getType() === 'mysql' ) { - $quote = '`'; - } else { - $quote = '"'; - } - - if ( $database !== null ) { - $database = $quote . $database . $quote . '.'; - } - - if ( $prefix === null ) { - $prefix = $this->dbPrefix(); - } - - return $database . $quote . $prefix . $table . $quote; - } - - function testTableNameLocal() { - $this->assertEquals( - $this->prefixAndQuote( 'tablename' ), - $this->db->tableName( 'tablename' ) - ); - } - - function testTableNameRawLocal() { - $this->assertEquals( - $this->prefixAndQuote( 'tablename', null, null, 'raw' ), - $this->db->tableName( 'tablename', 'raw' ) - ); - } - - function testTableNameShared() { - $this->assertEquals( - $this->prefixAndQuote( 'tablename', 'sharedatabase', 'sh_' ), - $this->getSharedTableName( 'tablename', 'sharedatabase', 'sh_' ) - ); - - $this->assertEquals( - $this->prefixAndQuote( 'tablename', 'sharedatabase', null ), - $this->getSharedTableName( 'tablename', 'sharedatabase', null ) - ); - } - - function testTableNameRawShared() { - $this->assertEquals( - $this->prefixAndQuote( 'tablename', 'sharedatabase', 'sh_', 'raw' ), - $this->getSharedTableName( 'tablename', 'sharedatabase', 'sh_', 'raw' ) - ); - - $this->assertEquals( - $this->prefixAndQuote( 'tablename', 'sharedatabase', null, 'raw' ), - $this->getSharedTableName( 'tablename', 'sharedatabase', null, 'raw' ) - ); - } - - function testTableNameForeign() { - $this->assertEquals( - $this->prefixAndQuote( 'tablename', 'databasename', '' ), - $this->db->tableName( 'databasename.tablename' ) - ); - } - - function testTableNameRawForeign() { - $this->assertEquals( - $this->prefixAndQuote( 'tablename', 'databasename', '', 'raw' ), - $this->db->tableName( 'databasename.tablename', 'raw' ) - ); - } - - function testFillPreparedEmpty() { - $sql = $this->db->fillPrepared( - 'SELECT * FROM interwiki', array() ); - $this->assertEquals( - "SELECT * FROM interwiki", - $sql ); - } - - function testFillPreparedQuestion() { - $sql = $this->db->fillPrepared( - 'SELECT * FROM cur WHERE cur_namespace=? AND cur_title=?', - array( 4, "Snicker's_paradox" ) ); - - $check = "SELECT * FROM cur WHERE cur_namespace='4' AND cur_title='Snicker''s_paradox'"; - if ( $this->db->getType() === 'mysql' ) { - $check = "SELECT * FROM cur WHERE cur_namespace='4' AND cur_title='Snicker\'s_paradox'"; - } - $this->assertEquals( $check, $sql ); - } - - function testFillPreparedBang() { - $sql = $this->db->fillPrepared( - 'SELECT user_id FROM ! WHERE user_name=?', - array( '"user"', "Slash's Dot" ) ); - - $check = "SELECT user_id FROM \"user\" WHERE user_name='Slash''s Dot'"; - if ( $this->db->getType() === 'mysql' ) { - $check = "SELECT user_id FROM \"user\" WHERE user_name='Slash\'s Dot'"; - } - $this->assertEquals( $check, $sql ); - } - - function testFillPreparedRaw() { - $sql = $this->db->fillPrepared( - "SELECT * FROM cur WHERE cur_title='This_\\&_that,_WTF\\?\\!'", - array( '"user"', "Slash's Dot" ) ); - $this->assertEquals( - "SELECT * FROM cur WHERE cur_title='This_&_that,_WTF?!'", - $sql ); - } - - /** - * @group Broken - */ - function testStoredFunctions() { - if ( !in_array( wfGetDB( DB_MASTER )->getType(), array( 'mysql', 'postgres' ) ) ) { - $this->markTestSkipped( 'MySQL or Postgres required' ); - } - global $IP; - $this->dropFunctions(); - $this->functionTest = true; - $this->assertTrue( $this->db->sourceFile( "$IP/tests/phpunit/data/db/{$this->db->getType()}/functions.sql" ) ); - $res = $this->db->query( 'SELECT mw_test_function() AS test', __METHOD__ ); - $this->assertEquals( 42, $res->fetchObject()->test ); - } - - private function dropFunctions() { - $this->db->query( 'DROP FUNCTION IF EXISTS mw_test_function' - . ( $this->db->getType() == 'postgres' ? '()' : '' ) - ); - } -} - - diff --git a/tests/phpunit/includes/db/ORMRowTest.php b/tests/phpunit/includes/db/ORMRowTest.php deleted file mode 100644 index 9dcaf2b3..00000000 --- a/tests/phpunit/includes/db/ORMRowTest.php +++ /dev/null @@ -1,234 +0,0 @@ - - */ -abstract class ORMRowTest extends \MediaWikiTestCase { - - /** - * @since 1.20 - * @return string - */ - protected abstract function getRowClass(); - - /** - * @since 1.20 - * @return IORMTable - */ - protected abstract function getTableInstance(); - - /** - * @since 1.20 - * @return array - */ - public abstract function constructorTestProvider(); - - /** - * @since 1.20 - * @param IORMRow $row - * @param array $data - */ - protected function verifyFields( IORMRow $row, array $data ) { - foreach ( array_keys( $data ) as $fieldName ) { - $this->assertEquals( $data[$fieldName], $row->getField( $fieldName ) ); - } - } - - /** - * @since 1.20 - * @param array $data - * @param boolean $loadDefaults - * @return IORMRow - */ - protected function getRowInstance( array $data, $loadDefaults ) { - $class = $this->getRowClass(); - return new $class( $this->getTableInstance(), $data, $loadDefaults ); - } - - /** - * @since 1.20 - * @return array - */ - protected function getMockValues() { - return array( - 'id' => 1, - 'str' => 'foobar4645645', - 'int' => 42, - 'float' => 4.2, - 'bool' => true, - 'array' => array( 42, 'foobar' ), - 'blob' => new stdClass() - ); - } - - /** - * @since 1.20 - * @return array - */ - protected function getMockFields() { - $mockValues = $this->getMockValues(); - $mockFields = array(); - - foreach ( $this->getTableInstance()->getFields() as $name => $type ) { - if ( $name !== 'id' ) { - $mockFields[$name] = $mockValues[$type]; - } - } - - return $mockFields; - } - - /** - * @since 1.20 - * @return array of IORMRow - */ - public function instanceProvider() { - $instances = array(); - - foreach ( $this->constructorTestProvider() as $arguments ) { - $instances[] = array( call_user_func_array( array( $this, 'getRowInstance' ), $arguments ) ); - } - - return $instances; - } - - /** - * @dataProvider constructorTestProvider - */ - public function testConstructor( array $data, $loadDefaults ) { - $this->verifyFields( $this->getRowInstance( $data, $loadDefaults ), $data ); - } - - /** - * @dataProvider constructorTestProvider - */ - public function testSave( array $data, $loadDefaults ) { - $item = $this->getRowInstance( $data, $loadDefaults ); - - $this->assertTrue( $item->save() ); - - $this->assertTrue( $item->hasIdField() ); - $this->assertTrue( is_integer( $item->getId() ) ); - - $id = $item->getId(); - - $this->assertTrue( $item->save() ); - - $this->assertEquals( $id, $item->getId() ); - - $this->verifyFields( $item, $data ); - } - - /** - * @dataProvider constructorTestProvider - */ - public function testRemove( array $data, $loadDefaults ) { - $item = $this->getRowInstance( $data, $loadDefaults ); - - $this->assertTrue( $item->save() ); - - $this->assertTrue( $item->remove() ); - - $this->assertFalse( $item->hasIdField() ); - - $this->assertTrue( $item->save() ); - - $this->verifyFields( $item, $data ); - - $this->assertTrue( $item->remove() ); - - $this->assertFalse( $item->hasIdField() ); - - $this->verifyFields( $item, $data ); - } - - /** - * @dataProvider instanceProvider - */ - public function testSetField( IORMRow $item ) { - foreach ( $this->getMockFields() as $name => $value ) { - $item->setField( $name, $value ); - $this->assertEquals( $value, $item->getField( $name ) ); - } - } - - /** - * @since 1.20 - * @param array $expected - * @param IORMRow $item - */ - protected function assertFieldValues( array $expected, IORMRow $item ) { - foreach ( $expected as $name => $type ) { - if ( $name !== 'id' ) { - $this->assertEquals( $expected[$name], $item->getField( $name ) ); - } - } - } - - /** - * @dataProvider instanceProvider - */ - public function testSetFields( IORMRow $item ) { - $originalValues = $item->getFields(); - - $item->setFields( array(), false ); - - foreach ( $item->getTable()->getFields() as $name => $type ) { - $originalHas = array_key_exists( $name, $originalValues ); - $newHas = $item->hasField( $name ); - - $this->assertEquals( $originalHas, $newHas ); - - if ( $originalHas && $newHas ) { - $this->assertEquals( $originalValues[$name], $item->getField( $name ) ); - } - } - - $mockFields = $this->getMockFields(); - - $item->setFields( $mockFields, false ); - - $this->assertFieldValues( $originalValues, $item ); - - $item->setFields( $mockFields, true ); - - $this->assertFieldValues( $mockFields, $item ); - } - - // TODO: test all of the methods! - -} \ No newline at end of file diff --git a/tests/phpunit/includes/db/TestORMRowTest.php b/tests/phpunit/includes/db/TestORMRowTest.php deleted file mode 100644 index afd1cb80..00000000 --- a/tests/phpunit/includes/db/TestORMRowTest.php +++ /dev/null @@ -1,174 +0,0 @@ - - */ -require_once __DIR__ . "/ORMRowTest.php"; - -class TestORMRowTest extends ORMRowTest { - - /** - * @since 1.20 - * @return string - */ - protected function getRowClass() { - return 'TestORMRow'; - } - - /** - * @since 1.20 - * @return IORMTable - */ - protected function getTableInstance() { - return TestORMTable::singleton(); - } - - public function setUp() { - parent::setUp(); - - $dbw = wfGetDB( DB_MASTER ); - - $isSqlite = $GLOBALS['wgDBtype'] === 'sqlite'; - - $idField = $isSqlite ? 'INTEGER' : 'INT unsigned'; - $primaryKey = $isSqlite ? 'PRIMARY KEY AUTOINCREMENT' : 'auto_increment PRIMARY KEY'; - - $dbw->query( - 'CREATE TABLE IF NOT EXISTS ' . $dbw->tableName( 'orm_test' ) . '( - test_id ' . $idField . ' NOT NULL ' . $primaryKey . ', - test_name VARCHAR(255) NOT NULL, - test_age TINYINT unsigned NOT NULL, - test_height FLOAT NOT NULL, - test_awesome TINYINT unsigned NOT NULL, - test_stuff BLOB NOT NULL, - test_moarstuff BLOB NOT NULL, - test_time varbinary(14) NOT NULL - );' - ); - } - - public function constructorTestProvider() { - return array( - array( - array( - 'name' => 'Foobar', - 'age' => 42, - 'height' => 9000.1, - 'awesome' => true, - 'stuff' => array( 13, 11, 7, 5, 3, 2 ), - 'moarstuff' => (object)array( 'foo' => 'bar', 'bar' => array( 4, 2 ), 'baz' => true ) - ), - true - ), - ); - } - -} - -class TestORMRow extends ORMRow {} - -class TestORMTable extends ORMTable { - - /** - * Returns the name of the database table objects of this type are stored in. - * - * @since 1.20 - * - * @return string - */ - public function getName() { - return 'orm_test'; - } - - /** - * Returns the name of a IORMRow implementing class that - * represents single rows in this table. - * - * @since 1.20 - * - * @return string - */ - public function getRowClass() { - return 'TestORMRow'; - } - - /** - * Returns an array with the fields and their types this object contains. - * This corresponds directly to the fields in the database, without prefix. - * - * field name => type - * - * Allowed types: - * * id - * * str - * * int - * * float - * * bool - * * array - * * blob - * - * @since 1.20 - * - * @return array - */ - public function getFields() { - return array( - 'id' => 'id', - 'name' => 'str', - 'age' => 'int', - 'height' => 'float', - 'awesome' => 'bool', - 'stuff' => 'array', - 'moarstuff' => 'blob', - 'time' => 'int', // TS_MW - ); - } - - /** - * Gets the db field prefix. - * - * @since 1.20 - * - * @return string - */ - protected function getFieldPrefix() { - return 'test_'; - } - - -} diff --git a/tests/phpunit/includes/debug/MWDebugTest.php b/tests/phpunit/includes/debug/MWDebugTest.php deleted file mode 100644 index 246b2918..00000000 --- a/tests/phpunit/includes/debug/MWDebugTest.php +++ /dev/null @@ -1,68 +0,0 @@ -assertEquals( array( array( - 'msg' => 'logging a string', - 'type' => 'log', - 'caller' => __METHOD__ , - ) ), - MWDebug::getLog() - ); - } - - function testAddWarning() { - MWDebug::warning( 'Warning message' ); - $this->assertEquals( array( array( - 'msg' => 'Warning message', - 'type' => 'warn', - 'caller' => 'MWDebugTest::testAddWarning', - ) ), - MWDebug::getLog() - ); - } - - function testAvoidDuplicateDeprecations() { - MWDebug::deprecated( 'wfOldFunction', '1.0', 'component' ); - MWDebug::deprecated( 'wfOldFunction', '1.0', 'component' ); - - // assertCount() not available on WMF integration server - $this->assertEquals( 1, - count( MWDebug::getLog() ), - "Only one deprecated warning per function should be kept" - ); - } - - function testAvoidNonConsecutivesDuplicateDeprecations() { - MWDebug::deprecated( 'wfOldFunction', '1.0', 'component' ); - MWDebug::warning( 'some warning' ); - MWDebug::log( 'we could have logged something too' ); - // Another deprecation - MWDebug::deprecated( 'wfOldFunction', '1.0', 'component' ); - - // assertCount() not available on WMF integration server - $this->assertEquals( 3, - count( MWDebug::getLog() ), - "Only one deprecated warning per function should be kept" - ); - } -} diff --git a/tests/phpunit/includes/filerepo/FileBackendTest.php b/tests/phpunit/includes/filerepo/FileBackendTest.php deleted file mode 100644 index a2dc5c6c..00000000 --- a/tests/phpunit/includes/filerepo/FileBackendTest.php +++ /dev/null @@ -1,1868 +0,0 @@ -getCliArg( 'use-filebackend=' ) ) { - if ( self::$backendToUse ) { - $this->singleBackend = self::$backendToUse; - } else { - $name = $this->getCliArg( 'use-filebackend=' ); - $useConfig = array(); - foreach ( $wgFileBackends as $conf ) { - if ( $conf['name'] == $name ) { - $useConfig = $conf; - break; - } - } - $useConfig['name'] = 'localtesting'; // swap name - $useConfig['shardViaHashLevels'] = array( // test sharding - 'unittest-cont1' => array( 'levels' => 1, 'base' => 16, 'repeat' => 1 ) - ); - $class = $useConfig['class']; - self::$backendToUse = new $class( $useConfig ); - $this->singleBackend = self::$backendToUse; - } - } else { - $this->singleBackend = new FSFileBackend( array( - 'name' => 'localtesting', - 'lockManager' => 'fsLockManager', - #'parallelize' => 'implicit', - 'containerPaths' => array( - 'unittest-cont1' => "{$tmpPrefix}-localtesting-cont1", - 'unittest-cont2' => "{$tmpPrefix}-localtesting-cont2" ) - ) ); - } - $this->multiBackend = new FileBackendMultiWrite( array( - 'name' => 'localtesting', - 'lockManager' => 'fsLockManager', - 'parallelize' => 'implicit', - 'backends' => array( - array( - 'name' => 'localmutlitesting1', - 'class' => 'FSFileBackend', - 'lockManager' => 'nullLockManager', - 'containerPaths' => array( - 'unittest-cont1' => "{$tmpPrefix}-localtestingmulti1-cont1", - 'unittest-cont2' => "{$tmpPrefix}-localtestingmulti1-cont2" ), - 'isMultiMaster' => false - ), - array( - 'name' => 'localmutlitesting2', - 'class' => 'FSFileBackend', - 'lockManager' => 'nullLockManager', - 'containerPaths' => array( - 'unittest-cont1' => "{$tmpPrefix}-localtestingmulti2-cont1", - 'unittest-cont2' => "{$tmpPrefix}-localtestingmulti2-cont2" ), - 'isMultiMaster' => true - ) - ) - ) ); - $this->filesToPrune = array(); - } - - private function baseStorePath() { - return 'mwstore://localtesting'; - } - - private function backendClass() { - return get_class( $this->backend ); - } - - /** - * @dataProvider provider_testIsStoragePath - */ - public function testIsStoragePath( $path, $isStorePath ) { - $this->assertEquals( $isStorePath, FileBackend::isStoragePath( $path ), - "FileBackend::isStoragePath on path '$path'" ); - } - - function provider_testIsStoragePath() { - return array( - array( 'mwstore://', true ), - array( 'mwstore://backend', true ), - array( 'mwstore://backend/container', true ), - array( 'mwstore://backend/container/', true ), - array( 'mwstore://backend/container/path', true ), - array( 'mwstore://backend//container/', true ), - array( 'mwstore://backend//container//', true ), - array( 'mwstore://backend//container//path', true ), - array( 'mwstore:///', true ), - array( 'mwstore:/', false ), - array( 'mwstore:', false ), - ); - } - - /** - * @dataProvider provider_testSplitStoragePath - */ - public function testSplitStoragePath( $path, $res ) { - $this->assertEquals( $res, FileBackend::splitStoragePath( $path ), - "FileBackend::splitStoragePath on path '$path'" ); - } - - function provider_testSplitStoragePath() { - return array( - array( 'mwstore://backend/container', array( 'backend', 'container', '' ) ), - array( 'mwstore://backend/container/', array( 'backend', 'container', '' ) ), - array( 'mwstore://backend/container/path', array( 'backend', 'container', 'path' ) ), - array( 'mwstore://backend/container//path', array( 'backend', 'container', '/path' ) ), - array( 'mwstore://backend//container/path', array( null, null, null ) ), - array( 'mwstore://backend//container//path', array( null, null, null ) ), - array( 'mwstore://', array( null, null, null ) ), - array( 'mwstore://backend', array( null, null, null ) ), - array( 'mwstore:///', array( null, null, null ) ), - array( 'mwstore:/', array( null, null, null ) ), - array( 'mwstore:', array( null, null, null ) ) - ); - } - - /** - * @dataProvider provider_normalizeStoragePath - */ - public function testNormalizeStoragePath( $path, $res ) { - $this->assertEquals( $res, FileBackend::normalizeStoragePath( $path ), - "FileBackend::normalizeStoragePath on path '$path'" ); - } - - function provider_normalizeStoragePath() { - return array( - array( 'mwstore://backend/container', 'mwstore://backend/container' ), - array( 'mwstore://backend/container/', 'mwstore://backend/container' ), - array( 'mwstore://backend/container/path', 'mwstore://backend/container/path' ), - array( 'mwstore://backend/container//path', 'mwstore://backend/container/path' ), - array( 'mwstore://backend/container///path', 'mwstore://backend/container/path' ), - array( 'mwstore://backend/container///path//to///obj', 'mwstore://backend/container/path/to/obj', - array( 'mwstore://', null ), - array( 'mwstore://backend', null ), - array( 'mwstore://backend//container/path', null ), - array( 'mwstore://backend//container//path', null ), - array( 'mwstore:///', null ), - array( 'mwstore:/', null ), - array( 'mwstore:', null ), ) - ); - } - - /** - * @dataProvider provider_testParentStoragePath - */ - public function testParentStoragePath( $path, $res ) { - $this->assertEquals( $res, FileBackend::parentStoragePath( $path ), - "FileBackend::parentStoragePath on path '$path'" ); - } - - function provider_testParentStoragePath() { - return array( - array( 'mwstore://backend/container/path/to/obj', 'mwstore://backend/container/path/to' ), - array( 'mwstore://backend/container/path/to', 'mwstore://backend/container/path' ), - array( 'mwstore://backend/container/path', 'mwstore://backend/container' ), - array( 'mwstore://backend/container', null ), - array( 'mwstore://backend/container/path/to/obj/', 'mwstore://backend/container/path/to' ), - array( 'mwstore://backend/container/path/to/', 'mwstore://backend/container/path' ), - array( 'mwstore://backend/container/path/', 'mwstore://backend/container' ), - array( 'mwstore://backend/container/', null ), - ); - } - - /** - * @dataProvider provider_testExtensionFromPath - */ - public function testExtensionFromPath( $path, $res ) { - $this->assertEquals( $res, FileBackend::extensionFromPath( $path ), - "FileBackend::extensionFromPath on path '$path'" ); - } - - function provider_testExtensionFromPath() { - return array( - array( 'mwstore://backend/container/path.txt', 'txt' ), - array( 'mwstore://backend/container/path.svg.png', 'png' ), - array( 'mwstore://backend/container/path', '' ), - array( 'mwstore://backend/container/path.', '' ), - ); - } - - /** - * @dataProvider provider_testStore - */ - public function testStore( $op ) { - $this->filesToPrune[] = $op['src']; - - $this->backend = $this->singleBackend; - $this->tearDownFiles(); - $this->doTestStore( $op ); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->tearDownFiles(); - $this->doTestStore( $op ); - $this->filesToPrune[] = $op['src']; # avoid file leaking - $this->tearDownFiles(); - } - - private function doTestStore( $op ) { - $backendName = $this->backendClass(); - - $source = $op['src']; - $dest = $op['dst']; - $this->prepare( array( 'dir' => dirname( $dest ) ) ); - - file_put_contents( $source, "Unit test file" ); - - if ( isset( $op['overwrite'] ) || isset( $op['overwriteSame'] ) ) { - $this->backend->store( $op ); - } - - $status = $this->backend->doOperation( $op ); - - $this->assertGoodStatus( $status, - "Store from $source to $dest succeeded without warnings ($backendName)." ); - $this->assertEquals( true, $status->isOK(), - "Store from $source to $dest succeeded ($backendName)." ); - $this->assertEquals( array( 0 => true ), $status->success, - "Store from $source to $dest has proper 'success' field in Status ($backendName)." ); - $this->assertEquals( true, file_exists( $source ), - "Source file $source still exists ($backendName)." ); - $this->assertEquals( true, $this->backend->fileExists( array( 'src' => $dest ) ), - "Destination file $dest exists ($backendName)." ); - - $this->assertEquals( filesize( $source ), - $this->backend->getFileSize( array( 'src' => $dest ) ), - "Destination file $dest has correct size ($backendName)." ); - - $props1 = FSFile::getPropsFromPath( $source ); - $props2 = $this->backend->getFileProps( array( 'src' => $dest ) ); - $this->assertEquals( $props1, $props2, - "Source and destination have the same props ($backendName)." ); - - $this->assertBackendPathsConsistent( array( $dest ) ); - } - - public function provider_testStore() { - $cases = array(); - - $tmpName = TempFSFile::factory( "unittests_", 'txt' )->getPath(); - $toPath = $this->baseStorePath() . '/unittest-cont1/e/fun/obj1.txt'; - $op = array( 'op' => 'store', 'src' => $tmpName, 'dst' => $toPath ); - $cases[] = array( - $op, // operation - $tmpName, // source - $toPath, // dest - ); - - $op2 = $op; - $op2['overwrite'] = true; - $cases[] = array( - $op2, // operation - $tmpName, // source - $toPath, // dest - ); - - $op2 = $op; - $op2['overwriteSame'] = true; - $cases[] = array( - $op2, // operation - $tmpName, // source - $toPath, // dest - ); - - return $cases; - } - - /** - * @dataProvider provider_testCopy - */ - public function testCopy( $op ) { - $this->backend = $this->singleBackend; - $this->tearDownFiles(); - $this->doTestCopy( $op ); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->tearDownFiles(); - $this->doTestCopy( $op ); - $this->tearDownFiles(); - } - - private function doTestCopy( $op ) { - $backendName = $this->backendClass(); - - $source = $op['src']; - $dest = $op['dst']; - $this->prepare( array( 'dir' => dirname( $source ) ) ); - $this->prepare( array( 'dir' => dirname( $dest ) ) ); - - $status = $this->backend->doOperation( - array( 'op' => 'create', 'content' => 'blahblah', 'dst' => $source ) ); - $this->assertGoodStatus( $status, - "Creation of file at $source succeeded ($backendName)." ); - - if ( isset( $op['overwrite'] ) || isset( $op['overwriteSame'] ) ) { - $this->backend->copy( $op ); - } - - $status = $this->backend->doOperation( $op ); - - $this->assertGoodStatus( $status, - "Copy from $source to $dest succeeded without warnings ($backendName)." ); - $this->assertEquals( true, $status->isOK(), - "Copy from $source to $dest succeeded ($backendName)." ); - $this->assertEquals( array( 0 => true ), $status->success, - "Copy from $source to $dest has proper 'success' field in Status ($backendName)." ); - $this->assertEquals( true, $this->backend->fileExists( array( 'src' => $source ) ), - "Source file $source still exists ($backendName)." ); - $this->assertEquals( true, $this->backend->fileExists( array( 'src' => $dest ) ), - "Destination file $dest exists after copy ($backendName)." ); - - $this->assertEquals( - $this->backend->getFileSize( array( 'src' => $source ) ), - $this->backend->getFileSize( array( 'src' => $dest ) ), - "Destination file $dest has correct size ($backendName)." ); - - $props1 = $this->backend->getFileProps( array( 'src' => $source ) ); - $props2 = $this->backend->getFileProps( array( 'src' => $dest ) ); - $this->assertEquals( $props1, $props2, - "Source and destination have the same props ($backendName)." ); - - $this->assertBackendPathsConsistent( array( $source, $dest ) ); - } - - public function provider_testCopy() { - $cases = array(); - - $source = $this->baseStorePath() . '/unittest-cont1/e/file.txt'; - $dest = $this->baseStorePath() . '/unittest-cont2/a/fileMoved.txt'; - - $op = array( 'op' => 'copy', 'src' => $source, 'dst' => $dest ); - $cases[] = array( - $op, // operation - $source, // source - $dest, // dest - ); - - $op2 = $op; - $op2['overwrite'] = true; - $cases[] = array( - $op2, // operation - $source, // source - $dest, // dest - ); - - $op2 = $op; - $op2['overwriteSame'] = true; - $cases[] = array( - $op2, // operation - $source, // source - $dest, // dest - ); - - return $cases; - } - - /** - * @dataProvider provider_testMove - */ - public function testMove( $op ) { - $this->backend = $this->singleBackend; - $this->tearDownFiles(); - $this->doTestMove( $op ); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->tearDownFiles(); - $this->doTestMove( $op ); - $this->tearDownFiles(); - } - - private function doTestMove( $op ) { - $backendName = $this->backendClass(); - - $source = $op['src']; - $dest = $op['dst']; - $this->prepare( array( 'dir' => dirname( $source ) ) ); - $this->prepare( array( 'dir' => dirname( $dest ) ) ); - - $status = $this->backend->doOperation( - array( 'op' => 'create', 'content' => 'blahblah', 'dst' => $source ) ); - $this->assertGoodStatus( $status, - "Creation of file at $source succeeded ($backendName)." ); - - if ( isset( $op['overwrite'] ) || isset( $op['overwriteSame'] ) ) { - $this->backend->copy( $op ); - } - - $status = $this->backend->doOperation( $op ); - $this->assertGoodStatus( $status, - "Move from $source to $dest succeeded without warnings ($backendName)." ); - $this->assertEquals( true, $status->isOK(), - "Move from $source to $dest succeeded ($backendName)." ); - $this->assertEquals( array( 0 => true ), $status->success, - "Move from $source to $dest has proper 'success' field in Status ($backendName)." ); - $this->assertEquals( false, $this->backend->fileExists( array( 'src' => $source ) ), - "Source file $source does not still exists ($backendName)." ); - $this->assertEquals( true, $this->backend->fileExists( array( 'src' => $dest ) ), - "Destination file $dest exists after move ($backendName)." ); - - $this->assertNotEquals( - $this->backend->getFileSize( array( 'src' => $source ) ), - $this->backend->getFileSize( array( 'src' => $dest ) ), - "Destination file $dest has correct size ($backendName)." ); - - $props1 = $this->backend->getFileProps( array( 'src' => $source ) ); - $props2 = $this->backend->getFileProps( array( 'src' => $dest ) ); - $this->assertEquals( false, $props1['fileExists'], - "Source file does not exist accourding to props ($backendName)." ); - $this->assertEquals( true, $props2['fileExists'], - "Destination file exists accourding to props ($backendName)." ); - - $this->assertBackendPathsConsistent( array( $source, $dest ) ); - } - - public function provider_testMove() { - $cases = array(); - - $source = $this->baseStorePath() . '/unittest-cont1/e/file.txt'; - $dest = $this->baseStorePath() . '/unittest-cont2/a/fileMoved.txt'; - - $op = array( 'op' => 'move', 'src' => $source, 'dst' => $dest ); - $cases[] = array( - $op, // operation - $source, // source - $dest, // dest - ); - - $op2 = $op; - $op2['overwrite'] = true; - $cases[] = array( - $op2, // operation - $source, // source - $dest, // dest - ); - - $op2 = $op; - $op2['overwriteSame'] = true; - $cases[] = array( - $op2, // operation - $source, // source - $dest, // dest - ); - - return $cases; - } - - /** - * @dataProvider provider_testDelete - */ - public function testDelete( $op, $withSource, $okStatus ) { - $this->backend = $this->singleBackend; - $this->tearDownFiles(); - $this->doTestDelete( $op, $withSource, $okStatus ); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->tearDownFiles(); - $this->doTestDelete( $op, $withSource, $okStatus ); - $this->tearDownFiles(); - } - - private function doTestDelete( $op, $withSource, $okStatus ) { - $backendName = $this->backendClass(); - - $source = $op['src']; - $this->prepare( array( 'dir' => dirname( $source ) ) ); - - if ( $withSource ) { - $status = $this->backend->doOperation( - array( 'op' => 'create', 'content' => 'blahblah', 'dst' => $source ) ); - $this->assertGoodStatus( $status, - "Creation of file at $source succeeded ($backendName)." ); - } - - $status = $this->backend->doOperation( $op ); - if ( $okStatus ) { - $this->assertGoodStatus( $status, - "Deletion of file at $source succeeded without warnings ($backendName)." ); - $this->assertEquals( true, $status->isOK(), - "Deletion of file at $source succeeded ($backendName)." ); - $this->assertEquals( array( 0 => true ), $status->success, - "Deletion of file at $source has proper 'success' field in Status ($backendName)." ); - } else { - $this->assertEquals( false, $status->isOK(), - "Deletion of file at $source failed ($backendName)." ); - } - - $this->assertEquals( false, $this->backend->fileExists( array( 'src' => $source ) ), - "Source file $source does not exist after move ($backendName)." ); - - $this->assertFalse( - $this->backend->getFileSize( array( 'src' => $source ) ), - "Source file $source has correct size (false) ($backendName)." ); - - $props1 = $this->backend->getFileProps( array( 'src' => $source ) ); - $this->assertFalse( $props1['fileExists'], - "Source file $source does not exist according to props ($backendName)." ); - - $this->assertBackendPathsConsistent( array( $source ) ); - } - - public function provider_testDelete() { - $cases = array(); - - $source = $this->baseStorePath() . '/unittest-cont1/e/myfacefile.txt'; - - $op = array( 'op' => 'delete', 'src' => $source ); - $cases[] = array( - $op, // operation - true, // with source - true // succeeds - ); - - $cases[] = array( - $op, // operation - false, // without source - false // fails - ); - - $op['ignoreMissingSource'] = true; - $cases[] = array( - $op, // operation - false, // without source - true // succeeds - ); - - return $cases; - } - - /** - * @dataProvider provider_testCreate - */ - public function testCreate( $op, $alreadyExists, $okStatus, $newSize ) { - $this->backend = $this->singleBackend; - $this->tearDownFiles(); - $this->doTestCreate( $op, $alreadyExists, $okStatus, $newSize ); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->tearDownFiles(); - $this->doTestCreate( $op, $alreadyExists, $okStatus, $newSize ); - $this->tearDownFiles(); - } - - private function doTestCreate( $op, $alreadyExists, $okStatus, $newSize ) { - $backendName = $this->backendClass(); - - $dest = $op['dst']; - $this->prepare( array( 'dir' => dirname( $dest ) ) ); - - $oldText = 'blah...blah...waahwaah'; - if ( $alreadyExists ) { - $status = $this->backend->doOperation( - array( 'op' => 'create', 'content' => $oldText, 'dst' => $dest ) ); - $this->assertGoodStatus( $status, - "Creation of file at $dest succeeded ($backendName)." ); - } - - $status = $this->backend->doOperation( $op ); - if ( $okStatus ) { - $this->assertGoodStatus( $status, - "Creation of file at $dest succeeded without warnings ($backendName)." ); - $this->assertEquals( true, $status->isOK(), - "Creation of file at $dest succeeded ($backendName)." ); - $this->assertEquals( array( 0 => true ), $status->success, - "Creation of file at $dest has proper 'success' field in Status ($backendName)." ); - } else { - $this->assertEquals( false, $status->isOK(), - "Creation of file at $dest failed ($backendName)." ); - } - - $this->assertEquals( true, $this->backend->fileExists( array( 'src' => $dest ) ), - "Destination file $dest exists after creation ($backendName)." ); - - $props1 = $this->backend->getFileProps( array( 'src' => $dest ) ); - $this->assertEquals( true, $props1['fileExists'], - "Destination file $dest exists according to props ($backendName)." ); - if ( $okStatus ) { // file content is what we saved - $this->assertEquals( $newSize, $props1['size'], - "Destination file $dest has expected size according to props ($backendName)." ); - $this->assertEquals( $newSize, - $this->backend->getFileSize( array( 'src' => $dest ) ), - "Destination file $dest has correct size ($backendName)." ); - } else { // file content is some other previous text - $this->assertEquals( strlen( $oldText ), $props1['size'], - "Destination file $dest has original size according to props ($backendName)." ); - $this->assertEquals( strlen( $oldText ), - $this->backend->getFileSize( array( 'src' => $dest ) ), - "Destination file $dest has original size according to props ($backendName)." ); - } - - $this->assertBackendPathsConsistent( array( $dest ) ); - } - - /** - * @dataProvider provider_testCreate - */ - public function provider_testCreate() { - $cases = array(); - - $dest = $this->baseStorePath() . '/unittest-cont2/a/myspacefile.txt'; - - $op = array( 'op' => 'create', 'content' => 'test test testing', 'dst' => $dest ); - $cases[] = array( - $op, // operation - false, // no dest already exists - true, // succeeds - strlen( $op['content'] ) - ); - - $op2 = $op; - $op2['content'] = "\n"; - $cases[] = array( - $op2, // operation - false, // no dest already exists - true, // succeeds - strlen( $op2['content'] ) - ); - - $op2 = $op; - $op2['content'] = "fsf\n waf 3kt"; - $cases[] = array( - $op2, // operation - true, // dest already exists - false, // fails - strlen( $op2['content'] ) - ); - - $op2 = $op; - $op2['content'] = "egm'g gkpe gpqg eqwgwqg"; - $op2['overwrite'] = true; - $cases[] = array( - $op2, // operation - true, // dest already exists - true, // succeeds - strlen( $op2['content'] ) - ); - - $op2 = $op; - $op2['content'] = "39qjmg3-qg"; - $op2['overwriteSame'] = true; - $cases[] = array( - $op2, // operation - true, // dest already exists - false, // succeeds - strlen( $op2['content'] ) - ); - - return $cases; - } - - public function testDoQuickOperations() { - $this->backend = $this->singleBackend; - $this->doTestDoQuickOperations(); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->doTestDoQuickOperations(); - $this->tearDownFiles(); - } - - private function doTestDoQuickOperations() { - $backendName = $this->backendClass(); - - $base = $this->baseStorePath(); - $files = array( - "$base/unittest-cont1/e/fileA.a", - "$base/unittest-cont1/e/fileB.a", - "$base/unittest-cont1/e/fileC.a" - ); - $ops = array(); - $purgeOps = array(); - foreach ( $files as $path ) { - $status = $this->prepare( array( 'dir' => dirname( $path ) ) ); - $this->assertGoodStatus( $status, - "Preparing $path succeeded without warnings ($backendName)." ); - $ops[] = array( 'op' => 'create', 'dst' => $path, 'content' => mt_rand(0,50000) ); - $purgeOps[] = array( 'op' => 'delete', 'src' => $path ); - } - $purgeOps[] = array( 'op' => 'null' ); - $status = $this->backend->doQuickOperations( $ops ); - $this->assertGoodStatus( $status, - "Creation of source files succeeded ($backendName)." ); - - foreach ( $files as $file ) { - $this->assertTrue( $this->backend->fileExists( array( 'src' => $file ) ), - "File $file exists." ); - } - - $status = $this->backend->doQuickOperations( $purgeOps ); - $this->assertGoodStatus( $status, - "Quick deletion of source files succeeded ($backendName)." ); - - foreach ( $files as $file ) { - $this->assertFalse( $this->backend->fileExists( array( 'src' => $file ) ), - "File $file purged." ); - } - } - - /** - * @dataProvider provider_testConcatenate - */ - public function testConcatenate( $op, $srcs, $srcsContent, $alreadyExists, $okStatus ) { - $this->filesToPrune[] = $op['dst']; - - $this->backend = $this->singleBackend; - $this->tearDownFiles(); - $this->doTestConcatenate( $op, $srcs, $srcsContent, $alreadyExists, $okStatus ); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->tearDownFiles(); - $this->doTestConcatenate( $op, $srcs, $srcsContent, $alreadyExists, $okStatus ); - $this->filesToPrune[] = $op['dst']; # avoid file leaking - $this->tearDownFiles(); - } - - private function doTestConcatenate( $params, $srcs, $srcsContent, $alreadyExists, $okStatus ) { - $backendName = $this->backendClass(); - - $expContent = ''; - // Create sources - $ops = array(); - foreach ( $srcs as $i => $source ) { - $this->prepare( array( 'dir' => dirname( $source ) ) ); - $ops[] = array( - 'op' => 'create', // operation - 'dst' => $source, // source - 'content' => $srcsContent[$i] - ); - $expContent .= $srcsContent[$i]; - } - $status = $this->backend->doOperations( $ops ); - - $this->assertGoodStatus( $status, - "Creation of source files succeeded ($backendName)." ); - - $dest = $params['dst']; - if ( $alreadyExists ) { - $ok = file_put_contents( $dest, 'blah...blah...waahwaah' ) !== false; - $this->assertEquals( true, $ok, - "Creation of file at $dest succeeded ($backendName)." ); - } else { - $ok = file_put_contents( $dest, '' ) !== false; - $this->assertEquals( true, $ok, - "Creation of 0-byte file at $dest succeeded ($backendName)." ); - } - - // Combine the files into one - $status = $this->backend->concatenate( $params ); - if ( $okStatus ) { - $this->assertGoodStatus( $status, - "Creation of concat file at $dest succeeded without warnings ($backendName)." ); - $this->assertEquals( true, $status->isOK(), - "Creation of concat file at $dest succeeded ($backendName)." ); - } else { - $this->assertEquals( false, $status->isOK(), - "Creation of concat file at $dest failed ($backendName)." ); - } - - if ( $okStatus ) { - $this->assertEquals( true, is_file( $dest ), - "Dest concat file $dest exists after creation ($backendName)." ); - } else { - $this->assertEquals( true, is_file( $dest ), - "Dest concat file $dest exists after failed creation ($backendName)." ); - } - - $contents = file_get_contents( $dest ); - $this->assertNotEquals( false, $contents, "File at $dest exists ($backendName)." ); - - if ( $okStatus ) { - $this->assertEquals( $expContent, $contents, - "Concat file at $dest has correct contents ($backendName)." ); - } else { - $this->assertNotEquals( $expContent, $contents, - "Concat file at $dest has correct contents ($backendName)." ); - } - } - - function provider_testConcatenate() { - $cases = array(); - - $rand = mt_rand( 0, 2000000000 ) . time(); - $dest = wfTempDir() . "/randomfile!$rand.txt"; - $srcs = array( - $this->baseStorePath() . '/unittest-cont1/e/file1.txt', - $this->baseStorePath() . '/unittest-cont1/e/file2.txt', - $this->baseStorePath() . '/unittest-cont1/e/file3.txt', - $this->baseStorePath() . '/unittest-cont1/e/file4.txt', - $this->baseStorePath() . '/unittest-cont1/e/file5.txt', - $this->baseStorePath() . '/unittest-cont1/e/file6.txt', - $this->baseStorePath() . '/unittest-cont1/e/file7.txt', - $this->baseStorePath() . '/unittest-cont1/e/file8.txt', - $this->baseStorePath() . '/unittest-cont1/e/file9.txt', - $this->baseStorePath() . '/unittest-cont1/e/file10.txt' - ); - $content = array( - 'egfage', - 'ageageag', - 'rhokohlr', - 'shgmslkg', - 'kenga', - 'owagmal', - 'kgmae', - 'g eak;g', - 'lkaem;a', - 'legma' - ); - $params = array( 'srcs' => $srcs, 'dst' => $dest ); - - $cases[] = array( - $params, // operation - $srcs, // sources - $content, // content for each source - false, // no dest already exists - true, // succeeds - ); - - $cases[] = array( - $params, // operation - $srcs, // sources - $content, // content for each source - true, // dest already exists - false, // succeeds - ); - - return $cases; - } - - /** - * @dataProvider provider_testGetFileStat - */ - public function testGetFileStat( $path, $content, $alreadyExists ) { - $this->backend = $this->singleBackend; - $this->tearDownFiles(); - $this->doTestGetFileStat( $path, $content, $alreadyExists ); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->tearDownFiles(); - $this->doTestGetFileStat( $path, $content, $alreadyExists ); - $this->tearDownFiles(); - } - - private function doTestGetFileStat( $path, $content, $alreadyExists ) { - $backendName = $this->backendClass(); - - if ( $alreadyExists ) { - $this->prepare( array( 'dir' => dirname( $path ) ) ); - $status = $this->create( array( 'dst' => $path, 'content' => $content ) ); - $this->assertGoodStatus( $status, - "Creation of file at $path succeeded ($backendName)." ); - - $size = $this->backend->getFileSize( array( 'src' => $path ) ); - $time = $this->backend->getFileTimestamp( array( 'src' => $path ) ); - $stat = $this->backend->getFileStat( array( 'src' => $path ) ); - - $this->assertEquals( strlen( $content ), $size, - "Correct file size of '$path'" ); - $this->assertTrue( abs( time() - wfTimestamp( TS_UNIX, $time ) ) < 10, - "Correct file timestamp of '$path'" ); - - $size = $stat['size']; - $time = $stat['mtime']; - $this->assertEquals( strlen( $content ), $size, - "Correct file size of '$path'" ); - $this->assertTrue( abs( time() - wfTimestamp( TS_UNIX, $time ) ) < 10, - "Correct file timestamp of '$path'" ); - - $this->backend->clearCache( array( $path ) ); - - $size = $this->backend->getFileSize( array( 'src' => $path ) ); - - $this->assertEquals( strlen( $content ), $size, - "Correct file size of '$path'" ); - - $this->backend->preloadCache( array( $path ) ); - - $size = $this->backend->getFileSize( array( 'src' => $path ) ); - - $this->assertEquals( strlen( $content ), $size, - "Correct file size of '$path'" ); - } else { - $size = $this->backend->getFileSize( array( 'src' => $path ) ); - $time = $this->backend->getFileTimestamp( array( 'src' => $path ) ); - $stat = $this->backend->getFileStat( array( 'src' => $path ) ); - - $this->assertFalse( $size, "Correct file size of '$path'" ); - $this->assertFalse( $time, "Correct file timestamp of '$path'" ); - $this->assertFalse( $stat, "Correct file stat of '$path'" ); - } - } - - function provider_testGetFileStat() { - $cases = array(); - - $base = $this->baseStorePath(); - $cases[] = array( "$base/unittest-cont1/e/b/z/some_file.txt", "some file contents", true ); - $cases[] = array( "$base/unittest-cont1/e/b/some-other_file.txt", "", true ); - $cases[] = array( "$base/unittest-cont1/e/b/some-diff_file.txt", null, false ); - - return $cases; - } - - /** - * @dataProvider provider_testGetFileContents - */ - public function testGetFileContents( $source, $content ) { - $this->backend = $this->singleBackend; - $this->tearDownFiles(); - $this->doTestGetFileContents( $source, $content ); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->tearDownFiles(); - $this->doTestGetFileContents( $source, $content ); - $this->tearDownFiles(); - } - - private function doTestGetFileContents( $source, $content ) { - $backendName = $this->backendClass(); - - $this->prepare( array( 'dir' => dirname( $source ) ) ); - - $status = $this->backend->doOperation( - array( 'op' => 'create', 'content' => $content, 'dst' => $source ) ); - $this->assertGoodStatus( $status, - "Creation of file at $source succeeded ($backendName)." ); - $this->assertEquals( true, $status->isOK(), - "Creation of file at $source succeeded with OK status ($backendName)." ); - - $newContents = $this->backend->getFileContents( array( 'src' => $source, 'latest' => 1 ) ); - $this->assertNotEquals( false, $newContents, - "Read of file at $source succeeded ($backendName)." ); - - $this->assertEquals( $content, $newContents, - "Contents read match data at $source ($backendName)." ); - } - - function provider_testGetFileContents() { - $cases = array(); - - $base = $this->baseStorePath(); - $cases[] = array( "$base/unittest-cont1/e/b/z/some_file.txt", "some file contents" ); - $cases[] = array( "$base/unittest-cont1/e/b/some-other_file.txt", "more file contents" ); - - return $cases; - } - - /** - * @dataProvider provider_testGetLocalCopy - */ - public function testGetLocalCopy( $source, $content ) { - $this->backend = $this->singleBackend; - $this->tearDownFiles(); - $this->doTestGetLocalCopy( $source, $content ); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->tearDownFiles(); - $this->doTestGetLocalCopy( $source, $content ); - $this->tearDownFiles(); - } - - private function doTestGetLocalCopy( $source, $content ) { - $backendName = $this->backendClass(); - - $this->prepare( array( 'dir' => dirname( $source ) ) ); - - $status = $this->backend->doOperation( - array( 'op' => 'create', 'content' => $content, 'dst' => $source ) ); - $this->assertGoodStatus( $status, - "Creation of file at $source succeeded ($backendName)." ); - - $tmpFile = $this->backend->getLocalCopy( array( 'src' => $source ) ); - $this->assertNotNull( $tmpFile, - "Creation of local copy of $source succeeded ($backendName)." ); - - $contents = file_get_contents( $tmpFile->getPath() ); - $this->assertNotEquals( false, $contents, "Local copy of $source exists ($backendName)." ); - } - - function provider_testGetLocalCopy() { - $cases = array(); - - $base = $this->baseStorePath(); - $cases[] = array( "$base/unittest-cont1/e/a/z/some_file.txt", "some file contents" ); - $cases[] = array( "$base/unittest-cont1/e/a/some-other_file.txt", "more file contents" ); - - return $cases; - } - - /** - * @dataProvider provider_testGetLocalReference - */ - public function testGetLocalReference( $source, $content ) { - $this->backend = $this->singleBackend; - $this->tearDownFiles(); - $this->doTestGetLocalReference( $source, $content ); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->tearDownFiles(); - $this->doTestGetLocalReference( $source, $content ); - $this->tearDownFiles(); - } - - private function doTestGetLocalReference( $source, $content ) { - $backendName = $this->backendClass(); - - $this->prepare( array( 'dir' => dirname( $source ) ) ); - - $status = $this->create( array( 'content' => $content, 'dst' => $source ) ); - $this->assertGoodStatus( $status, - "Creation of file at $source succeeded ($backendName)." ); - - $tmpFile = $this->backend->getLocalReference( array( 'src' => $source ) ); - $this->assertNotNull( $tmpFile, - "Creation of local copy of $source succeeded ($backendName)." ); - - $contents = file_get_contents( $tmpFile->getPath() ); - $this->assertNotEquals( false, $contents, "Local copy of $source exists ($backendName)." ); - } - - function provider_testGetLocalReference() { - $cases = array(); - - $base = $this->baseStorePath(); - $cases[] = array( "$base/unittest-cont1/e/a/z/some_file.txt", "some file contents" ); - $cases[] = array( "$base/unittest-cont1/e/a/some-other_file.txt", "more file contents" ); - - return $cases; - } - - /** - * @dataProvider provider_testPrepareAndClean - */ - public function testPrepareAndClean( $path, $isOK ) { - $this->backend = $this->singleBackend; - $this->doTestPrepareAndClean( $path, $isOK ); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->doTestPrepareAndClean( $path, $isOK ); - $this->tearDownFiles(); - } - - function provider_testPrepareAndClean() { - $base = $this->baseStorePath(); - return array( - array( "$base/unittest-cont1/e/a/z/some_file1.txt", true ), - array( "$base/unittest-cont2/a/z/some_file2.txt", true ), - # Specific to FS backend with no basePath field set - #array( "$base/unittest-cont3/a/z/some_file3.txt", false ), - ); - } - - private function doTestPrepareAndClean( $path, $isOK ) { - $backendName = $this->backendClass(); - - $status = $this->prepare( array( 'dir' => dirname( $path ) ) ); - if ( $isOK ) { - $this->assertGoodStatus( $status, - "Preparing dir $path succeeded without warnings ($backendName)." ); - $this->assertEquals( true, $status->isOK(), - "Preparing dir $path succeeded ($backendName)." ); - } else { - $this->assertEquals( false, $status->isOK(), - "Preparing dir $path failed ($backendName)." ); - } - - $status = $this->backend->clean( array( 'dir' => dirname( $path ) ) ); - if ( $isOK ) { - $this->assertGoodStatus( $status, - "Cleaning dir $path succeeded without warnings ($backendName)." ); - $this->assertEquals( true, $status->isOK(), - "Cleaning dir $path succeeded ($backendName)." ); - } else { - $this->assertEquals( false, $status->isOK(), - "Cleaning dir $path failed ($backendName)." ); - } - } - - public function testRecursiveClean() { - $this->backend = $this->singleBackend; - $this->doTestRecursiveClean(); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->doTestRecursiveClean(); - $this->tearDownFiles(); - } - - private function doTestRecursiveClean() { - $backendName = $this->backendClass(); - - $base = $this->baseStorePath(); - $dirs = array( - "$base/unittest-cont1/e/a", - "$base/unittest-cont1/e/a/b", - "$base/unittest-cont1/e/a/b/c", - "$base/unittest-cont1/e/a/b/c/d0", - "$base/unittest-cont1/e/a/b/c/d1", - "$base/unittest-cont1/e/a/b/c/d2", - "$base/unittest-cont1/e/a/b/c/d0/1", - "$base/unittest-cont1/e/a/b/c/d0/2", - "$base/unittest-cont1/e/a/b/c/d1/3", - "$base/unittest-cont1/e/a/b/c/d1/4", - "$base/unittest-cont1/e/a/b/c/d2/5", - "$base/unittest-cont1/e/a/b/c/d2/6" - ); - foreach ( $dirs as $dir ) { - $status = $this->prepare( array( 'dir' => $dir ) ); - $this->assertGoodStatus( $status, - "Preparing dir $dir succeeded without warnings ($backendName)." ); - } - - if ( $this->backend instanceof FSFileBackend ) { - foreach ( $dirs as $dir ) { - $this->assertEquals( true, $this->backend->directoryExists( array( 'dir' => $dir ) ), - "Dir $dir exists ($backendName)." ); - } - } - - $status = $this->backend->clean( - array( 'dir' => "$base/unittest-cont1", 'recursive' => 1 ) ); - $this->assertGoodStatus( $status, - "Recursive cleaning of dir $dir succeeded without warnings ($backendName)." ); - - foreach ( $dirs as $dir ) { - $this->assertEquals( false, $this->backend->directoryExists( array( 'dir' => $dir ) ), - "Dir $dir no longer exists ($backendName)." ); - } - } - - // @TODO: testSecure - - public function testDoOperations() { - $this->backend = $this->singleBackend; - $this->tearDownFiles(); - $this->doTestDoOperations(); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->tearDownFiles(); - $this->doTestDoOperations(); - $this->tearDownFiles(); - } - - private function doTestDoOperations() { - $base = $this->baseStorePath(); - - $fileA = "$base/unittest-cont1/e/a/b/fileA.txt"; - $fileAContents = '3tqtmoeatmn4wg4qe-mg3qt3 tq'; - $fileB = "$base/unittest-cont1/e/a/b/fileB.txt"; - $fileBContents = 'g-jmq3gpqgt3qtg q3GT '; - $fileC = "$base/unittest-cont1/e/a/b/fileC.txt"; - $fileCContents = 'eigna[ogmewt 3qt g3qg flew[ag'; - $fileD = "$base/unittest-cont1/e/a/b/fileD.txt"; - - $this->prepare( array( 'dir' => dirname( $fileA ) ) ); - $this->create( array( 'dst' => $fileA, 'content' => $fileAContents ) ); - $this->prepare( array( 'dir' => dirname( $fileB ) ) ); - $this->create( array( 'dst' => $fileB, 'content' => $fileBContents ) ); - $this->prepare( array( 'dir' => dirname( $fileC ) ) ); - $this->create( array( 'dst' => $fileC, 'content' => $fileCContents ) ); - $this->prepare( array( 'dir' => dirname( $fileD ) ) ); - - $status = $this->backend->doOperations( array( - array( 'op' => 'copy', 'src' => $fileA, 'dst' => $fileC, 'overwrite' => 1 ), - // Now: A:, B:, C:, D: (file:) - array( 'op' => 'copy', 'src' => $fileC, 'dst' => $fileA, 'overwriteSame' => 1 ), - // Now: A:, B:, C:, D: - array( 'op' => 'move', 'src' => $fileC, 'dst' => $fileD, 'overwrite' => 1 ), - // Now: A:, B:, C:, D: - array( 'op' => 'move', 'src' => $fileB, 'dst' => $fileC ), - // Now: A:, B:, C:, D: - array( 'op' => 'move', 'src' => $fileD, 'dst' => $fileA, 'overwriteSame' => 1 ), - // Now: A:, B:, C:, D: - array( 'op' => 'move', 'src' => $fileC, 'dst' => $fileA, 'overwrite' => 1 ), - // Now: A:, B:, C:, D: - array( 'op' => 'copy', 'src' => $fileA, 'dst' => $fileC ), - // Now: A:, B:, C:, D: - array( 'op' => 'move', 'src' => $fileA, 'dst' => $fileC, 'overwriteSame' => 1 ), - // Now: A:, B:, C:, D: - array( 'op' => 'copy', 'src' => $fileC, 'dst' => $fileC, 'overwrite' => 1 ), - // Does nothing - array( 'op' => 'copy', 'src' => $fileC, 'dst' => $fileC, 'overwriteSame' => 1 ), - // Does nothing - array( 'op' => 'move', 'src' => $fileC, 'dst' => $fileC, 'overwrite' => 1 ), - // Does nothing - array( 'op' => 'move', 'src' => $fileC, 'dst' => $fileC, 'overwriteSame' => 1 ), - // Does nothing - array( 'op' => 'null' ), - // Does nothing - ) ); - - $this->assertGoodStatus( $status, "Operation batch succeeded" ); - $this->assertEquals( true, $status->isOK(), "Operation batch succeeded" ); - $this->assertEquals( 13, count( $status->success ), - "Operation batch has correct success array" ); - - $this->assertEquals( false, $this->backend->fileExists( array( 'src' => $fileA ) ), - "File does not exist at $fileA" ); - $this->assertEquals( false, $this->backend->fileExists( array( 'src' => $fileB ) ), - "File does not exist at $fileB" ); - $this->assertEquals( false, $this->backend->fileExists( array( 'src' => $fileD ) ), - "File does not exist at $fileD" ); - - $this->assertEquals( true, $this->backend->fileExists( array( 'src' => $fileC ) ), - "File exists at $fileC" ); - $this->assertEquals( $fileBContents, - $this->backend->getFileContents( array( 'src' => $fileC ) ), - "Correct file contents of $fileC" ); - $this->assertEquals( strlen( $fileBContents ), - $this->backend->getFileSize( array( 'src' => $fileC ) ), - "Correct file size of $fileC" ); - $this->assertEquals( wfBaseConvert( sha1( $fileBContents ), 16, 36, 31 ), - $this->backend->getFileSha1Base36( array( 'src' => $fileC ) ), - "Correct file SHA-1 of $fileC" ); - } - - public function testDoOperationsPipeline() { - $this->backend = $this->singleBackend; - $this->tearDownFiles(); - $this->doTestDoOperationsPipeline(); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->tearDownFiles(); - $this->doTestDoOperationsPipeline(); - $this->tearDownFiles(); - } - - // concurrency orientated - private function doTestDoOperationsPipeline() { - $base = $this->baseStorePath(); - - $fileAContents = '3tqtmoeatmn4wg4qe-mg3qt3 tq'; - $fileBContents = 'g-jmq3gpqgt3qtg q3GT '; - $fileCContents = 'eigna[ogmewt 3qt g3qg flew[ag'; - - $tmpNameA = TempFSFile::factory( "unittests_", 'txt' )->getPath(); - file_put_contents( $tmpNameA, $fileAContents ); - $tmpNameB = TempFSFile::factory( "unittests_", 'txt' )->getPath(); - file_put_contents( $tmpNameB, $fileBContents ); - $tmpNameC = TempFSFile::factory( "unittests_", 'txt' )->getPath(); - file_put_contents( $tmpNameC, $fileCContents ); - - $this->filesToPrune[] = $tmpNameA; # avoid file leaking - $this->filesToPrune[] = $tmpNameB; # avoid file leaking - $this->filesToPrune[] = $tmpNameC; # avoid file leaking - - $fileA = "$base/unittest-cont1/e/a/b/fileA.txt"; - $fileB = "$base/unittest-cont1/e/a/b/fileB.txt"; - $fileC = "$base/unittest-cont1/e/a/b/fileC.txt"; - $fileD = "$base/unittest-cont1/e/a/b/fileD.txt"; - - $this->prepare( array( 'dir' => dirname( $fileA ) ) ); - $this->create( array( 'dst' => $fileA, 'content' => $fileAContents ) ); - $this->prepare( array( 'dir' => dirname( $fileB ) ) ); - $this->prepare( array( 'dir' => dirname( $fileC ) ) ); - $this->prepare( array( 'dir' => dirname( $fileD ) ) ); - - $status = $this->backend->doOperations( array( - array( 'op' => 'store', 'src' => $tmpNameA, 'dst' => $fileA, 'overwriteSame' => 1 ), - array( 'op' => 'store', 'src' => $tmpNameB, 'dst' => $fileB, 'overwrite' => 1 ), - array( 'op' => 'store', 'src' => $tmpNameC, 'dst' => $fileC, 'overwrite' => 1 ), - array( 'op' => 'copy', 'src' => $fileA, 'dst' => $fileC, 'overwrite' => 1 ), - // Now: A:, B:, C:, D: (file:) - array( 'op' => 'copy', 'src' => $fileC, 'dst' => $fileA, 'overwriteSame' => 1 ), - // Now: A:, B:, C:, D: - array( 'op' => 'move', 'src' => $fileC, 'dst' => $fileD, 'overwrite' => 1 ), - // Now: A:, B:, C:, D: - array( 'op' => 'move', 'src' => $fileB, 'dst' => $fileC ), - // Now: A:, B:, C:, D: - array( 'op' => 'move', 'src' => $fileD, 'dst' => $fileA, 'overwriteSame' => 1 ), - // Now: A:, B:, C:, D: - array( 'op' => 'move', 'src' => $fileC, 'dst' => $fileA, 'overwrite' => 1 ), - // Now: A:, B:, C:, D: - array( 'op' => 'copy', 'src' => $fileA, 'dst' => $fileC ), - // Now: A:, B:, C:, D: - array( 'op' => 'move', 'src' => $fileA, 'dst' => $fileC, 'overwriteSame' => 1 ), - // Now: A:, B:, C:, D: - array( 'op' => 'copy', 'src' => $fileC, 'dst' => $fileC, 'overwrite' => 1 ), - // Does nothing - array( 'op' => 'copy', 'src' => $fileC, 'dst' => $fileC, 'overwriteSame' => 1 ), - // Does nothing - array( 'op' => 'move', 'src' => $fileC, 'dst' => $fileC, 'overwrite' => 1 ), - // Does nothing - array( 'op' => 'move', 'src' => $fileC, 'dst' => $fileC, 'overwriteSame' => 1 ), - // Does nothing - array( 'op' => 'null' ), - // Does nothing - ) ); - - $this->assertGoodStatus( $status, "Operation batch succeeded" ); - $this->assertEquals( true, $status->isOK(), "Operation batch succeeded" ); - $this->assertEquals( 16, count( $status->success ), - "Operation batch has correct success array" ); - - $this->assertEquals( false, $this->backend->fileExists( array( 'src' => $fileA ) ), - "File does not exist at $fileA" ); - $this->assertEquals( false, $this->backend->fileExists( array( 'src' => $fileB ) ), - "File does not exist at $fileB" ); - $this->assertEquals( false, $this->backend->fileExists( array( 'src' => $fileD ) ), - "File does not exist at $fileD" ); - - $this->assertEquals( true, $this->backend->fileExists( array( 'src' => $fileC ) ), - "File exists at $fileC" ); - $this->assertEquals( $fileBContents, - $this->backend->getFileContents( array( 'src' => $fileC ) ), - "Correct file contents of $fileC" ); - $this->assertEquals( strlen( $fileBContents ), - $this->backend->getFileSize( array( 'src' => $fileC ) ), - "Correct file size of $fileC" ); - $this->assertEquals( wfBaseConvert( sha1( $fileBContents ), 16, 36, 31 ), - $this->backend->getFileSha1Base36( array( 'src' => $fileC ) ), - "Correct file SHA-1 of $fileC" ); - } - - public function testDoOperationsFailing() { - $this->backend = $this->singleBackend; - $this->tearDownFiles(); - $this->doTestDoOperationsFailing(); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->tearDownFiles(); - $this->doTestDoOperationsFailing(); - $this->tearDownFiles(); - } - - private function doTestDoOperationsFailing() { - $base = $this->baseStorePath(); - - $fileA = "$base/unittest-cont2/a/b/fileA.txt"; - $fileAContents = '3tqtmoeatmn4wg4qe-mg3qt3 tq'; - $fileB = "$base/unittest-cont2/a/b/fileB.txt"; - $fileBContents = 'g-jmq3gpqgt3qtg q3GT '; - $fileC = "$base/unittest-cont2/a/b/fileC.txt"; - $fileCContents = 'eigna[ogmewt 3qt g3qg flew[ag'; - $fileD = "$base/unittest-cont2/a/b/fileD.txt"; - - $this->prepare( array( 'dir' => dirname( $fileA ) ) ); - $this->create( array( 'dst' => $fileA, 'content' => $fileAContents ) ); - $this->prepare( array( 'dir' => dirname( $fileB ) ) ); - $this->create( array( 'dst' => $fileB, 'content' => $fileBContents ) ); - $this->prepare( array( 'dir' => dirname( $fileC ) ) ); - $this->create( array( 'dst' => $fileC, 'content' => $fileCContents ) ); - - $status = $this->backend->doOperations( array( - array( 'op' => 'copy', 'src' => $fileA, 'dst' => $fileC, 'overwrite' => 1 ), - // Now: A:, B:, C:, D: (file:) - array( 'op' => 'copy', 'src' => $fileC, 'dst' => $fileA, 'overwriteSame' => 1 ), - // Now: A:, B:, C:, D: - array( 'op' => 'copy', 'src' => $fileB, 'dst' => $fileD, 'overwrite' => 1 ), - // Now: A:, B:, C:, D: - array( 'op' => 'move', 'src' => $fileC, 'dst' => $fileD ), - // Now: A:, B:, C:, D: (failed) - array( 'op' => 'move', 'src' => $fileB, 'dst' => $fileC, 'overwriteSame' => 1 ), - // Now: A:, B:, C:, D: (failed) - array( 'op' => 'move', 'src' => $fileB, 'dst' => $fileA, 'overwrite' => 1 ), - // Now: A:, B:, C:, D: - array( 'op' => 'delete', 'src' => $fileD ), - // Now: A:, B:, C:, D: - array( 'op' => 'null' ), - // Does nothing - ), array( 'force' => 1 ) ); - - $this->assertNotEquals( array(), $status->errors, "Operation had warnings" ); - $this->assertEquals( true, $status->isOK(), "Operation batch succeeded" ); - $this->assertEquals( 8, count( $status->success ), - "Operation batch has correct success array" ); - - $this->assertEquals( false, $this->backend->fileExists( array( 'src' => $fileB ) ), - "File does not exist at $fileB" ); - $this->assertEquals( false, $this->backend->fileExists( array( 'src' => $fileD ) ), - "File does not exist at $fileD" ); - - $this->assertEquals( true, $this->backend->fileExists( array( 'src' => $fileA ) ), - "File does not exist at $fileA" ); - $this->assertEquals( true, $this->backend->fileExists( array( 'src' => $fileC ) ), - "File exists at $fileC" ); - $this->assertEquals( $fileBContents, - $this->backend->getFileContents( array( 'src' => $fileA ) ), - "Correct file contents of $fileA" ); - $this->assertEquals( strlen( $fileBContents ), - $this->backend->getFileSize( array( 'src' => $fileA ) ), - "Correct file size of $fileA" ); - $this->assertEquals( wfBaseConvert( sha1( $fileBContents ), 16, 36, 31 ), - $this->backend->getFileSha1Base36( array( 'src' => $fileA ) ), - "Correct file SHA-1 of $fileA" ); - } - - public function testGetFileList() { - $this->backend = $this->singleBackend; - $this->tearDownFiles(); - $this->doTestGetFileList(); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->tearDownFiles(); - $this->doTestGetFileList(); - $this->tearDownFiles(); - } - - private function doTestGetFileList() { - $backendName = $this->backendClass(); - $base = $this->baseStorePath(); - - // Should have no errors - $iter = $this->backend->getFileList( array( 'dir' => "$base/unittest-cont-notexists" ) ); - - $files = array( - "$base/unittest-cont1/e/test1.txt", - "$base/unittest-cont1/e/test2.txt", - "$base/unittest-cont1/e/test3.txt", - "$base/unittest-cont1/e/subdir1/test1.txt", - "$base/unittest-cont1/e/subdir1/test2.txt", - "$base/unittest-cont1/e/subdir2/test3.txt", - "$base/unittest-cont1/e/subdir2/test4.txt", - "$base/unittest-cont1/e/subdir2/subdir/test1.txt", - "$base/unittest-cont1/e/subdir2/subdir/test2.txt", - "$base/unittest-cont1/e/subdir2/subdir/test3.txt", - "$base/unittest-cont1/e/subdir2/subdir/test4.txt", - "$base/unittest-cont1/e/subdir2/subdir/test5.txt", - "$base/unittest-cont1/e/subdir2/subdir/sub/test0.txt", - "$base/unittest-cont1/e/subdir2/subdir/sub/120-px-file.txt", - ); - - // Add the files - $ops = array(); - foreach ( $files as $file ) { - $this->prepare( array( 'dir' => dirname( $file ) ) ); - $ops[] = array( 'op' => 'create', 'content' => 'xxy', 'dst' => $file ); - } - $status = $this->backend->doQuickOperations( $ops ); - $this->assertGoodStatus( $status, - "Creation of files succeeded ($backendName)." ); - $this->assertEquals( true, $status->isOK(), - "Creation of files succeeded with OK status ($backendName)." ); - - // Expected listing - $expected = array( - "e/test1.txt", - "e/test2.txt", - "e/test3.txt", - "e/subdir1/test1.txt", - "e/subdir1/test2.txt", - "e/subdir2/test3.txt", - "e/subdir2/test4.txt", - "e/subdir2/subdir/test1.txt", - "e/subdir2/subdir/test2.txt", - "e/subdir2/subdir/test3.txt", - "e/subdir2/subdir/test4.txt", - "e/subdir2/subdir/test5.txt", - "e/subdir2/subdir/sub/test0.txt", - "e/subdir2/subdir/sub/120-px-file.txt", - ); - sort( $expected ); - - // Actual listing (no trailing slash) - $list = array(); - $iter = $this->backend->getFileList( array( 'dir' => "$base/unittest-cont1" ) ); - foreach ( $iter as $file ) { - $list[] = $file; - } - sort( $list ); - - $this->assertEquals( $expected, $list, "Correct file listing ($backendName)." ); - - // Actual listing (with trailing slash) - $list = array(); - $iter = $this->backend->getFileList( array( 'dir' => "$base/unittest-cont1/" ) ); - foreach ( $iter as $file ) { - $list[] = $file; - } - sort( $list ); - - $this->assertEquals( $expected, $list, "Correct file listing ($backendName)." ); - - // Expected listing - $expected = array( - "test1.txt", - "test2.txt", - "test3.txt", - "test4.txt", - "test5.txt", - "sub/test0.txt", - "sub/120-px-file.txt", - ); - sort( $expected ); - - // Actual listing (no trailing slash) - $list = array(); - $iter = $this->backend->getFileList( array( 'dir' => "$base/unittest-cont1/e/subdir2/subdir" ) ); - foreach ( $iter as $file ) { - $list[] = $file; - } - sort( $list ); - - $this->assertEquals( $expected, $list, "Correct file listing ($backendName)." ); - - // Actual listing (with trailing slash) - $list = array(); - $iter = $this->backend->getFileList( array( 'dir' => "$base/unittest-cont1/e/subdir2/subdir/" ) ); - foreach ( $iter as $file ) { - $list[] = $file; - } - sort( $list ); - - $this->assertEquals( $expected, $list, "Correct file listing ($backendName)." ); - - // Actual listing (using iterator second time) - $list = array(); - foreach ( $iter as $file ) { - $list[] = $file; - } - sort( $list ); - - $this->assertEquals( $expected, $list, "Correct file listing ($backendName), second iteration." ); - - // Expected listing (top files only) - $expected = array( - "test1.txt", - "test2.txt", - "test3.txt", - "test4.txt", - "test5.txt" - ); - sort( $expected ); - - // Actual listing (top files only) - $list = array(); - $iter = $this->backend->getTopFileList( array( 'dir' => "$base/unittest-cont1/e/subdir2/subdir" ) ); - foreach ( $iter as $file ) { - $list[] = $file; - } - sort( $list ); - - $this->assertEquals( $expected, $list, "Correct top file listing ($backendName)." ); - - foreach ( $files as $file ) { // clean up - $this->backend->doOperation( array( 'op' => 'delete', 'src' => $file ) ); - } - - $iter = $this->backend->getFileList( array( 'dir' => "$base/unittest-cont1/not/exists" ) ); - foreach ( $iter as $iter ) {} // no errors - } - - public function testGetDirectoryList() { - $this->backend = $this->singleBackend; - $this->tearDownFiles(); - $this->doTestGetDirectoryList(); - $this->tearDownFiles(); - - $this->backend = $this->multiBackend; - $this->tearDownFiles(); - $this->doTestGetDirectoryList(); - $this->tearDownFiles(); - } - - private function doTestGetDirectoryList() { - $backendName = $this->backendClass(); - - $base = $this->baseStorePath(); - $files = array( - "$base/unittest-cont1/e/test1.txt", - "$base/unittest-cont1/e/test2.txt", - "$base/unittest-cont1/e/test3.txt", - "$base/unittest-cont1/e/subdir1/test1.txt", - "$base/unittest-cont1/e/subdir1/test2.txt", - "$base/unittest-cont1/e/subdir2/test3.txt", - "$base/unittest-cont1/e/subdir2/test4.txt", - "$base/unittest-cont1/e/subdir2/subdir/test1.txt", - "$base/unittest-cont1/e/subdir3/subdir/test2.txt", - "$base/unittest-cont1/e/subdir4/subdir/test3.txt", - "$base/unittest-cont1/e/subdir4/subdir/test4.txt", - "$base/unittest-cont1/e/subdir4/subdir/test5.txt", - "$base/unittest-cont1/e/subdir4/subdir/sub/test0.txt", - "$base/unittest-cont1/e/subdir4/subdir/sub/120-px-file.txt", - ); - - // Add the files - $ops = array(); - foreach ( $files as $file ) { - $this->prepare( array( 'dir' => dirname( $file ) ) ); - $ops[] = array( 'op' => 'create', 'content' => 'xxy', 'dst' => $file ); - } - $status = $this->backend->doQuickOperations( $ops ); - $this->assertGoodStatus( $status, - "Creation of files succeeded ($backendName)." ); - $this->assertEquals( true, $status->isOK(), - "Creation of files succeeded with OK status ($backendName)." ); - - $this->assertEquals( true, - $this->backend->directoryExists( array( 'dir' => "$base/unittest-cont1/e/subdir1" ) ), - "Directory exists in ($backendName)." ); - $this->assertEquals( true, - $this->backend->directoryExists( array( 'dir' => "$base/unittest-cont1/e/subdir2/subdir" ) ), - "Directory exists in ($backendName)." ); - $this->assertEquals( false, - $this->backend->directoryExists( array( 'dir' => "$base/unittest-cont1/e/subdir2/test1.txt" ) ), - "Directory does not exists in ($backendName)." ); - - // Expected listing - $expected = array( - "e", - ); - sort( $expected ); - - // Actual listing (no trailing slash) - $list = array(); - $iter = $this->backend->getTopDirectoryList( array( 'dir' => "$base/unittest-cont1" ) ); - foreach ( $iter as $file ) { - $list[] = $file; - } - sort( $list ); - - $this->assertEquals( $expected, $list, "Correct top dir listing ($backendName)." ); - - // Expected listing - $expected = array( - "subdir1", - "subdir2", - "subdir3", - "subdir4", - ); - sort( $expected ); - - // Actual listing (no trailing slash) - $list = array(); - $iter = $this->backend->getTopDirectoryList( array( 'dir' => "$base/unittest-cont1/e" ) ); - foreach ( $iter as $file ) { - $list[] = $file; - } - sort( $list ); - - $this->assertEquals( $expected, $list, "Correct top dir listing ($backendName)." ); - - // Actual listing (with trailing slash) - $list = array(); - $iter = $this->backend->getTopDirectoryList( array( 'dir' => "$base/unittest-cont1/e/" ) ); - foreach ( $iter as $file ) { - $list[] = $file; - } - sort( $list ); - - $this->assertEquals( $expected, $list, "Correct top dir listing ($backendName)." ); - - // Expected listing - $expected = array( - "subdir", - ); - sort( $expected ); - - // Actual listing (no trailing slash) - $list = array(); - $iter = $this->backend->getTopDirectoryList( array( 'dir' => "$base/unittest-cont1/e/subdir2" ) ); - foreach ( $iter as $file ) { - $list[] = $file; - } - sort( $list ); - - $this->assertEquals( $expected, $list, "Correct top dir listing ($backendName)." ); - - // Actual listing (with trailing slash) - $list = array(); - $iter = $this->backend->getTopDirectoryList( array( 'dir' => "$base/unittest-cont1/e/subdir2/" ) ); - foreach ( $iter as $file ) { - $list[] = $file; - } - sort( $list ); - - $this->assertEquals( $expected, $list, "Correct top dir listing ($backendName)." ); - - // Actual listing (using iterator second time) - $list = array(); - foreach ( $iter as $file ) { - $list[] = $file; - } - sort( $list ); - - $this->assertEquals( $expected, $list, "Correct top dir listing ($backendName), second iteration." ); - - // Expected listing (recursive) - $expected = array( - "e", - "e/subdir1", - "e/subdir2", - "e/subdir3", - "e/subdir4", - "e/subdir2/subdir", - "e/subdir3/subdir", - "e/subdir4/subdir", - "e/subdir4/subdir/sub", - ); - sort( $expected ); - - // Actual listing (recursive) - $list = array(); - $iter = $this->backend->getDirectoryList( array( 'dir' => "$base/unittest-cont1/" ) ); - foreach ( $iter as $file ) { - $list[] = $file; - } - sort( $list ); - - $this->assertEquals( $expected, $list, "Correct dir listing ($backendName)." ); - - // Expected listing (recursive) - $expected = array( - "subdir", - "subdir/sub", - ); - sort( $expected ); - - // Actual listing (recursive) - $list = array(); - $iter = $this->backend->getDirectoryList( array( 'dir' => "$base/unittest-cont1/e/subdir4" ) ); - foreach ( $iter as $file ) { - $list[] = $file; - } - sort( $list ); - - $this->assertEquals( $expected, $list, "Correct dir listing ($backendName)." ); - - // Actual listing (recursive, second time) - $list = array(); - foreach ( $iter as $file ) { - $list[] = $file; - } - sort( $list ); - - $this->assertEquals( $expected, $list, "Correct dir listing ($backendName)." ); - - foreach ( $files as $file ) { // clean up - $this->backend->doOperation( array( 'op' => 'delete', 'src' => $file ) ); - } - - $iter = $this->backend->getDirectoryList( array( 'dir' => "$base/unittest-cont1/not/exists" ) ); - foreach ( $iter as $iter ) {} // no errors - } - - public function testLockCalls() { - $this->backend = $this->singleBackend; - $this->doTestLockCalls(); - } - - private function doTestLockCalls() { - $backendName = $this->backendClass(); - - for ( $i=0; $i<50; $i++ ) { - $paths = array( - "test1.txt", - "test2.txt", - "test3.txt", - "subdir1", - "subdir1", // duplicate - "subdir1/test1.txt", - "subdir1/test2.txt", - "subdir2", - "subdir2", // duplicate - "subdir2/test3.txt", - "subdir2/test4.txt", - "subdir2/subdir", - "subdir2/subdir/test1.txt", - "subdir2/subdir/test2.txt", - "subdir2/subdir/test3.txt", - "subdir2/subdir/test4.txt", - "subdir2/subdir/test5.txt", - "subdir2/subdir/sub", - "subdir2/subdir/sub/test0.txt", - "subdir2/subdir/sub/120-px-file.txt", - ); - - $status = $this->backend->lockFiles( $paths, LockManager::LOCK_EX ); - $this->assertEquals( array(), $status->errors, - "Locking of files succeeded ($backendName)." ); - $this->assertEquals( true, $status->isOK(), - "Locking of files succeeded with OK status ($backendName)." ); - - $status = $this->backend->lockFiles( $paths, LockManager::LOCK_SH ); - $this->assertEquals( array(), $status->errors, - "Locking of files succeeded ($backendName)." ); - $this->assertEquals( true, $status->isOK(), - "Locking of files succeeded with OK status ($backendName)." ); - - $status = $this->backend->unlockFiles( $paths, LockManager::LOCK_SH ); - $this->assertEquals( array(), $status->errors, - "Locking of files succeeded ($backendName)." ); - $this->assertEquals( true, $status->isOK(), - "Locking of files succeeded with OK status ($backendName)." ); - - $status = $this->backend->unlockFiles( $paths, LockManager::LOCK_EX ); - $this->assertEquals( array(), $status->errors, - "Locking of files succeeded ($backendName)." ); - $this->assertEquals( true, $status->isOK(), - "Locking of files succeeded with OK status ($backendName)." ); - } - } - - // test helper wrapper for backend prepare() function - private function prepare( array $params ) { - return $this->backend->prepare( $params ); - } - - // test helper wrapper for backend prepare() function - private function create( array $params ) { - $params['op'] = 'create'; - return $this->backend->doQuickOperations( array( $params ) ); - } - - function tearDownFiles() { - foreach ( $this->filesToPrune as $file ) { - @unlink( $file ); - } - $containers = array( 'unittest-cont1', 'unittest-cont2', 'unittest-cont3' ); - foreach ( $containers as $container ) { - $this->deleteFiles( $container ); - } - $this->filesToPrune = array(); - } - - private function deleteFiles( $container ) { - $base = $this->baseStorePath(); - $iter = $this->backend->getFileList( array( 'dir' => "$base/$container" ) ); - if ( $iter ) { - foreach ( $iter as $file ) { - $this->backend->delete( array( 'src' => "$base/$container/$file" ), - array( 'force' => 1, 'nonLocking' => 1 ) ); - } - } - $this->backend->clean( array( 'dir' => "$base/$container", 'recursive' => 1 ) ); - } - - function assertBackendPathsConsistent( array $paths ) { - if ( $this->backend instanceof FileBackendMultiWrite ) { - $status = $this->backend->consistencyCheck( $paths ); - $this->assertGoodStatus( $status, "Files synced: " . implode( ',', $paths ) ); - } - } - - function assertGoodStatus( $status, $msg ) { - $this->assertEquals( print_r( array(), 1 ), print_r( $status->errors, 1 ), $msg ); - } - - function tearDown() { - parent::tearDown(); - } -} diff --git a/tests/phpunit/includes/filerepo/FileRepoTest.php b/tests/phpunit/includes/filerepo/FileRepoTest.php deleted file mode 100644 index 8f92c123..00000000 --- a/tests/phpunit/includes/filerepo/FileRepoTest.php +++ /dev/null @@ -1,45 +0,0 @@ - 'foobar' - ) ); - } - /** - * @expectedException MWException - */ - function testFileRepoConstructionOptionNeedBackendKey() { - $f = new FileRepo( array( - 'name' => 'foobar' - ) ); - } - - function testFileRepoConstructionWithRequiredOptions() { - $f = new FileRepo( array( - 'name' => 'FileRepoTestRepository', - 'backend' => new FSFileBackend( array( - 'name' => 'local-testing', - 'lockManager' => 'nullLockManager', - 'containerPaths' => array() - ) ) - ) ); - $this->assertInstanceOf( 'FileRepo', $f ); - } -} diff --git a/tests/phpunit/includes/filerepo/StoreBatchTest.php b/tests/phpunit/includes/filerepo/StoreBatchTest.php deleted file mode 100644 index 3ab56af8..00000000 --- a/tests/phpunit/includes/filerepo/StoreBatchTest.php +++ /dev/null @@ -1,123 +0,0 @@ -getCliArg( 'use-filebackend=' ) ) { - $name = $this->getCliArg( 'use-filebackend=' ); - $useConfig = array(); - foreach ( $wgFileBackends as $conf ) { - if ( $conf['name'] == $name ) { - $useConfig = $conf; - } - } - $useConfig['name'] = 'local-testing'; // swap name - $class = $useConfig['class']; - $backend = new $class( $useConfig ); - } else { - $backend = new FSFileBackend( array( - 'name' => 'local-testing', - 'lockManager' => 'nullLockManager', - 'containerPaths' => array( - 'unittests-public' => "{$tmpPrefix}-public", - 'unittests-thumb' => "{$tmpPrefix}-thumb", - 'unittests-temp' => "{$tmpPrefix}-temp", - 'unittests-deleted' => "{$tmpPrefix}-deleted", - ) - ) ); - } - $this->repo = new FileRepo( array( - 'name' => 'unittests', - 'backend' => $backend - ) ); - - $this->date = gmdate( "YmdHis" ); - $this->createdFiles = array(); - } - - /** - * Store a file or virtual URL source into a media file name. - * - * @param $originalName string The title of the image - * @param $srcPath string The filepath or virtual URL - * @param $flags integer Flags to pass into repo::store(). - */ - private function storeit($originalName, $srcPath, $flags) { - $hashPath = $this->repo->getHashPath( $originalName ); - $dstRel = "$hashPath{$this->date}!$originalName"; - $dstUrlRel = $hashPath . $this->date . '!' . rawurlencode( $originalName ); - - $result = $this->repo->store( $srcPath, 'temp', $dstRel, $flags ); - $result->value = $this->repo->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel; - $this->createdFiles[] = $result->value; - return $result; - } - - /** - * Test storing a file using different flags. - * - * @param $fn string The title of the image - * @param $infn string The name of the file (in the filesystem) - * @param $otherfn string The name of the different file (in the filesystem) - * @param $fromrepo logical 'true' if we want to copy from a virtual URL out of the Repo. - */ - private function storecohort($fn, $infn, $otherfn, $fromrepo) { - $f = $this->storeit( $fn, $infn, 0 ); - $this->assertTrue( $f->isOK(), 'failed to store a new file' ); - $this->assertEquals( $f->failCount, 0, "counts wrong {$f->successCount} {$f->failCount}" ); - $this->assertEquals( $f->successCount, 1 , "counts wrong {$f->successCount} {$f->failCount}" ); - if ( $fromrepo ) { - $f = $this->storeit( "Other-$fn", $infn, FileRepo::OVERWRITE); - $infn = $f->value; - } - // This should work because we're allowed to overwrite - $f = $this->storeit( $fn, $infn, FileRepo::OVERWRITE ); - $this->assertTrue( $f->isOK(), 'We should be allowed to overwrite' ); - $this->assertEquals( $f->failCount, 0, "counts wrong {$f->successCount} {$f->failCount}" ); - $this->assertEquals( $f->successCount, 1 , "counts wrong {$f->successCount} {$f->failCount}" ); - // This should fail because we're overwriting. - $f = $this->storeit( $fn, $infn, 0 ); - $this->assertFalse( $f->isOK(), 'We should not be allowed to overwrite' ); - $this->assertEquals( $f->failCount, 1, "counts wrong {$f->successCount} {$f->failCount}" ); - $this->assertEquals( $f->successCount, 0 , "counts wrong {$f->successCount} {$f->failCount}" ); - // This should succeed because we're overwriting the same content. - $f = $this->storeit( $fn, $infn, FileRepo::OVERWRITE_SAME ); - $this->assertTrue( $f->isOK(), 'We should be able to overwrite the same content' ); - $this->assertEquals( $f->failCount, 0, "counts wrong {$f->successCount} {$f->failCount}" ); - $this->assertEquals( $f->successCount, 1 , "counts wrong {$f->successCount} {$f->failCount}" ); - // This should fail because we're overwriting different content. - if ( $fromrepo ) { - $f = $this->storeit( "Other-$fn", $otherfn, FileRepo::OVERWRITE); - $otherfn = $f->value; - } - $f = $this->storeit( $fn, $otherfn, FileRepo::OVERWRITE_SAME ); - $this->assertFalse( $f->isOK(), 'We should not be allowed to overwrite different content' ); - $this->assertEquals( $f->failCount, 1, "counts wrong {$f->successCount} {$f->failCount}" ); - $this->assertEquals( $f->successCount, 0 , "counts wrong {$f->successCount} {$f->failCount}" ); - } - - public function teststore() { - global $IP; - $this->storecohort( "Test1.png", "$IP/skins/monobook/wiki.png", "$IP/skins/monobook/video.png", false ); - $this->storecohort( "Test2.png", "$IP/skins/monobook/wiki.png", "$IP/skins/monobook/video.png", true ); - } - - public function tearDown() { - $this->repo->cleanupBatch( $this->createdFiles ); // delete files - foreach ( $this->createdFiles as $tmp ) { // delete dirs - $tmp = $this->repo->resolveVirtualUrl( $tmp ); - while ( $tmp = FileBackend::parentStoragePath( $tmp ) ) { - $this->repo->getBackend()->clean( array( 'dir' => $tmp ) ); - } - } - parent::tearDown(); - } -} diff --git a/tests/phpunit/includes/installer/InstallDocFormatterTest.php b/tests/phpunit/includes/installer/InstallDocFormatterTest.php deleted file mode 100644 index 56485d3e..00000000 --- a/tests/phpunit/includes/installer/InstallDocFormatterTest.php +++ /dev/null @@ -1,64 +0,0 @@ -assertEquals( - $expected, - InstallDocFormatter::format( $unformattedText ), - $message - ); - } - - /** - * Provider for testFormat() - */ - function provideDocFormattingTests() { - # Format: (expected string, unformattedText string, optional message) - return array( - # Escape some wikitext - array( 'Install <tag>' , 'Install ', 'Escaping <' ), - array( 'Install {{template}}' , 'Install {{template}}', 'Escaping [[' ), - array( 'Install [[page]]' , 'Install [[page]]', 'Escaping {{' ), - array( 'Install ' , "Install \r", 'Removing \r' ), - - # Transform \t{1,2} into :{1,2} - array( ':One indentation', "\tOne indentation", 'Replacing a single \t' ), - array( '::Two indentations', "\t\tTwo indentations", 'Replacing 2 x \t' ), - - # Transform 'bug 123' links - array( - '[https://bugzilla.wikimedia.org/123 bug 123]', - 'bug 123', 'Testing bug 123 links' ), - array( - '([https://bugzilla.wikimedia.org/987654 bug 987654])', - '(bug 987654)', 'Testing (bug 987654) links' ), - - # "bug abc" shouldn't work - array( 'bug foobar', 'bug foobar', "Don't match bug followed by non-digits" ), - array( 'bug !!fakefake!!', 'bug !!fakefake!!', "Don't match bug followed by non-digits" ), - - # Transform '$wgFooBar' links - array( - '[http://www.mediawiki.org/wiki/Manual:$wgFooBar $wgFooBar]', - '$wgFooBar', 'Testing basic $wgFooBar' ), - array( - '[http://www.mediawiki.org/wiki/Manual:$wgFooBar45 $wgFooBar45]', - '$wgFooBar45', 'Testing $wgFooBar45 (with numbers)' ), - array( - '[http://www.mediawiki.org/wiki/Manual:$wgFoo_Bar $wgFoo_Bar]', - '$wgFoo_Bar', 'Testing $wgFoo_Bar (with underscore)' ), - - # Icky variables that shouldn't link - array( '$myAwesomeVariable', '$myAwesomeVariable', 'Testing $myAwesomeVariable (not starting with $wg)' ), - array( '$()not!a&Var', '$()not!a&Var', 'Testing $()not!a&Var (obviously not a variable)' ), - ); - } -} diff --git a/tests/phpunit/includes/json/ServicesJsonTest.php b/tests/phpunit/includes/json/ServicesJsonTest.php deleted file mode 100644 index 8f2421a2..00000000 --- a/tests/phpunit/includes/json/ServicesJsonTest.php +++ /dev/null @@ -1,93 +0,0 @@ -encode() - * produce the same output - * - * @dataProvider provideValuesToEncode - */ - public function testJsonEncode( $input, $desc ) { - if ( !function_exists( 'json_encode' ) ) { - $this->markTestIncomplete( 'No PHP json support, unable to test' ); - return; - } elseif( strtolower( json_encode( "\xf0\xa0\x80\x80" ) ) != '"\ud840\udc00"' ) { - $this->markTestIncomplete( 'Have buggy PHP json support, unable to test' ); - return; - } else { - $jsonObj = new Services_JSON(); - $this->assertEquals( - $jsonObj->encode( $input ), - json_encode( $input ), - $desc - ); - } - } - - /** - * Test to make sure core json_decode() and our Services_Json()->decode() - * produce the same output - * - * @dataProvider provideValuesToDecode - */ - public function testJsonDecode( $input, $desc ) { - if ( !function_exists( 'json_decode' ) ) { - $this->markTestIncomplete( 'No PHP json support, unable to test' ); - return; - } else { - $jsonObj = new Services_JSON(); - $this->assertEquals( - $jsonObj->decode( $input ), - json_decode( $input ), - $desc - ); - } - } - - function provideValuesToEncode() { - $obj = new stdClass(); - $obj->property = 'value'; - $obj->property2 = null; - $obj->property3 = 1.234; - return array( - array( 1, 'basic integer' ), - array( -1, 'negative integer' ), - array( 1.1, 'basic float' ), - array( true, 'basic bool true' ), - array( false, 'basic bool false' ), - array( 'some string', 'basic string test' ), - array( "some string\nwith newline", 'newline string test' ), - array( '♥ü', 'unicode string test' ), - array( array( 'some', 'string', 'values' ), 'basic array of strings' ), - array( array( 'key1' => 'val1', 'key2' => 'val2' ), 'array with string keys' ), - array( array( 1 => 'val1', 3 => 'val2', '2' => 'val3' ), 'out of order numbered array test' ), - array( array(), 'empty array test' ), - array( $obj, 'basic object test' ), - array( new stdClass, 'empty object test' ), - array( null, 'null test' ), - ); - } - - function provideValuesToDecode() { - return array( - array( '1', 'basic integer' ), - array( '-1', 'negative integer' ), - array( '1.1', 'basic float' ), - array( '1.1e1', 'scientific float' ), - array( 'true', 'basic bool true' ), - array( 'false', 'basic bool false' ), - array( '"some string"', 'basic string test' ), - array( '"some string\nwith newline"', 'newline string test' ), - array( '"♥ü"', 'unicode character string test' ), - array( '"\u2665"', 'unicode \\u string test' ), - array( '["some","string","values"]', 'basic array of strings' ), - array( '[]', 'empty array test' ), - array( '{"key":"value"}', 'Basic key => value test' ), - array( '{}', 'empty object test' ), - array( 'null', 'null test' ), - ); - } -} diff --git a/tests/phpunit/includes/libs/CSSJanusTest.php b/tests/phpunit/includes/libs/CSSJanusTest.php deleted file mode 100644 index 54f66077..00000000 --- a/tests/phpunit/includes/libs/CSSJanusTest.php +++ /dev/null @@ -1,560 +0,0 @@ -assertEquals( $transformedA, $cssB, 'Test A-B transformation' ); - - $transformedB = CSSJanus::transform( $cssB ); - $this->assertEquals( $transformedB, $cssA, 'Test B-A transformation' ); - - // If no B version is provided, it means - // the output should equal the input. - } else { - $transformedA = CSSJanus::transform( $cssA ); - $this->assertEquals( $transformedA, $cssA, 'Nothing was flipped' ); - } - } - - /** - * @dataProvider provideTransformAdvancedCases - */ - function testTransformAdvanced( $code, $expectedOutput, $options = array() ) { - $swapLtrRtlInURL = isset( $options['swapLtrRtlInURL'] ) ? $options['swapLtrRtlInURL'] : false; - $swapLeftRightInURL = isset( $options['swapLeftRightInURL'] ) ? $options['swapLeftRightInURL'] : false; - - $flipped = CSSJanus::transform( $code, $swapLtrRtlInURL, $swapLeftRightInURL ); - - $this->assertEquals( $expectedOutput, $flipped, - 'Test flipping, options: url-ltr-rtl=' . ($swapLtrRtlInURL ? 'true' : 'false') - . ' url-left-right=' . ($swapLeftRightInURL ? 'true' : 'false') - ); - } - /** - * @dataProvider provideTransformBrokenCases - * @group Broken - */ - function testTransformBroken( $code, $expectedOutput ) { - $flipped = CSSJanus::transform( $code ); - - $this->assertEquals( $expectedOutput, $flipped, 'Test flipping' ); - } - - /** - * These transform cases are tested *in both directions* - * No need to declare a principle twice in both directions here. - */ - function provideTransformCases() { - return array( - // Property keys - array( - '.foo { left: 0; }', - '.foo { right: 0; }' - ), - // Guard against partial keys - // (CSS currently doesn't have flippable properties - // that contain the direction as part of the key without - // dash separation) - array( - '.foo { alright: 0; }' - ), - array( - '.foo { balleft: 0; }' - ), - - // Dashed property keys - array( - '.foo { padding-left: 0; }', - '.foo { padding-right: 0; }' - ), - array( - '.foo { margin-left: 0; }', - '.foo { margin-right: 0; }' - ), - array( - '.foo { border-left: 0; }', - '.foo { border-right: 0; }' - ), - - // Double-dashed property keys - array( - '.foo { border-left-color: red; }', - '.foo { border-right-color: red; }' - ), - array( - // Includes unknown properties? - '.foo { x-left-y: 0; }', - '.foo { x-right-y: 0; }' - ), - - // Multi-value properties - array( - '.foo { padding: 0; }' - ), - array( - '.foo { padding: 0 1px; }' - ), - array( - '.foo { padding: 0 1px 2px; }' - ), - array( - '.foo { padding: 0 1px 2px 3px; }', - '.foo { padding: 0 3px 2px 1px; }' - ), - - // Shorthand / Four notation - array( - '.foo { padding: .25em 15px 0pt 0ex; }', - '.foo { padding: .25em 0ex 0pt 15px; }' - ), - array( - '.foo { margin: 1px -4px 3px 2px; }', - '.foo { margin: 1px 2px 3px -4px; }' - ), - array( - '.foo { padding: 0 15px .25em 0; }', - '.foo { padding: 0 0 .25em 15px; }' - ), - array( - '.foo { padding: 1px 4.1grad 3px 2%; }', - '.foo { padding: 1px 2% 3px 4.1grad; }' - ), - array( - '.foo { padding: 1px 2px 3px auto; }', - '.foo { padding: 1px auto 3px 2px; }' - ), - array( - '.foo { padding: 1px inherit 3px auto; }', - '.foo { padding: 1px auto 3px inherit; }' - ), - array( - '.foo { border-radius: .25em 15px 0pt 0ex; }', - '.foo { border-radius: .25em 0ex 0pt 15px; }' - ), - array( - '.foo { x-unknown: a b c d; }' - ), - array( - '.foo barpx 0 2% { opacity: 0; }' - ), - array( - '#settings td p strong' - ), - array( - # Not sure how 4+ values should behave, - # testing to make sure changes are detected - '.foo { x-unknown: 1 2 3 4 5; }', - '.foo { x-unknown: 1 4 3 2 5; }', - ), - array( - '.foo { x-unknown: 1 2 3 4 5 6; }', - '.foo { x-unknown: 1 4 3 2 5 6; }', - ), - - // Shorthand / Three notation - array( - '.foo { margin: 1em 0 .25em; }' - ), - array( - '.foo { margin:-1.5em 0 -.75em; }' - ), - - // Shorthand / Two notation - array( - '.foo { padding: 1px 2px; }' - ), - - // Shorthand / One notation - array( - '.foo { padding: 1px; }' - ), - - // Direction - // Note: This differs from the Python implementation, - // see also CSSJanus::fixDirection for more info. - array( - '.foo { direction: ltr; }', - '.foo { direction: rtl; }' - ), - array( - '.foo { direction: rtl; }', - '.foo { direction: ltr; }' - ), - array( - 'input { direction: ltr; }', - 'input { direction: rtl; }' - ), - array( - 'input { direction: rtl; }', - 'input { direction: ltr; }' - ), - array( - 'body { direction: ltr; }', - 'body { direction: rtl; }' - ), - array( - '.foo, body, input { direction: ltr; }', - '.foo, body, input { direction: rtl; }' - ), - array( - 'body { padding: 10px; direction: ltr; }', - 'body { padding: 10px; direction: rtl; }' - ), - array( - 'body { direction: ltr } .myClass { direction: ltr }', - 'body { direction: rtl } .myClass { direction: rtl }' - ), - - // Left/right values - array( - '.foo { float: left; }', - '.foo { float: right; }' - ), - array( - '.foo { text-align: left; }', - '.foo { text-align: right; }' - ), - array( - '.foo { -x-unknown: left; }', - '.foo { -x-unknown: right; }' - ), - // Guard against selectors that look flippable - array( - '.column-left { width: 0; }' - ), - array( - 'a.left { width: 0; }' - ), - array( - 'a.leftification { width: 0; }' - ), - array( - 'a.ltr { width: 0; }' - ), - array( - #
- '.a-ltr.png { width: 0; }' - ), - array( - # - 'foo-ltr[attr="x"] { width: 0; }' - ), - array( - 'div.left > span.right+span.left { width: 0; }' - ), - array( - '.thisclass .left .myclass { width: 0; }' - ), - array( - '.thisclass .left .myclass #myid { width: 0; }' - ), - - // Cursor values (east/west) - array( - '.foo { cursor: e-resize; }', - '.foo { cursor: w-resize; }' - ), - array( - '.foo { cursor: se-resize; }', - '.foo { cursor: sw-resize; }' - ), - array( - '.foo { cursor: ne-resize; }', - '.foo { cursor: nw-resize; }' - ), - - // Background - array( - '.foo { background-position: top left; }', - '.foo { background-position: top right; }' - ), - array( - '.foo { background: url(/foo/bar.png) top left; }', - '.foo { background: url(/foo/bar.png) top right; }' - ), - array( - '.foo { background: url(/foo/bar.png) top left no-repeat; }', - '.foo { background: url(/foo/bar.png) top right no-repeat; }' - ), - array( - '.foo { background: url(/foo/bar.png) no-repeat top left; }', - '.foo { background: url(/foo/bar.png) no-repeat top right; }' - ), - array( - '.foo { background: #fff url(/foo/bar.png) no-repeat top left; }', - '.foo { background: #fff url(/foo/bar.png) no-repeat top right; }' - ), - array( - '.foo { background-position: 100% 40%; }', - '.foo { background-position: 0% 40%; }' - ), - array( - '.foo { background-position: 23% 0; }', - '.foo { background-position: 77% 0; }' - ), - array( - '.foo { background-position: 23% auto; }', - '.foo { background-position: 77% auto; }' - ), - array( - '.foo { background-position-x: 23%; }', - '.foo { background-position-x: 77%; }' - ), - array( - '.foo { background-position-y: 23%; }', - '.foo { background-position-y: 23%; }' - ), - array( - '.foo { background:url(../foo.png) no-repeat 75% 50%; }', - '.foo { background:url(../foo.png) no-repeat 25% 50%; }' - ), - array( - '.foo { background: 10% 20% } .bar { background: 40% 30% }', - '.foo { background: 90% 20% } .bar { background: 60% 30% }' - ), - - // Multiple rules - array( - 'body { direction: rtl; float: right; } .foo { direction: ltr; float: right; }', - 'body { direction: ltr; float: left; } .foo { direction: rtl; float: left; }', - ), - - // Duplicate properties - array( - '.foo { float: left; float: right; float: left; }', - '.foo { float: right; float: left; float: right; }', - ), - - // Preserve comments - array( - '/* left /* right */left: 10px', - '/* left /* right */right: 10px' - ), - array( - '/*left*//*left*/left: 10px', - '/*left*//*left*/right: 10px' - ), - array( - '/* Going right is cool */ .foo { width: 0 }', - ), - array( - "/* padding-right 1 2 3 4 */\n#test { width: 0}\n/*right*/" - ), - array( - "/** Two line comment\n * left\n \*/\n#test {width: 0}" - ), - - // @noflip annotation - array( - // before selector (single) - '/* @noflip */ div { float: left; }' - ), - array( - // before selector (multiple) - '/* @noflip */ div, .notme { float: left; }' - ), - array( - // inside selector - 'div, /* @noflip */ .foo { float: left; }' - ), - array( - // after selector - 'div, .notme /* @noflip */ { float: left; }' - ), - array( - // before multiple rules - '/* @noflip */ div { float: left; } .foo { float: left; }', - '/* @noflip */ div { float: left; } .foo { float: right; }' - ), - array( - // after multiple rules - '.foo { float: left; } /* @noflip */ div { float: left; }', - '.foo { float: right; } /* @noflip */ div { float: left; }' - ), - array( - // before multiple properties - 'div { /* @noflip */ float: left; text-align: left; }', - 'div { /* @noflip */ float: left; text-align: right; }' - ), - array( - // after multiple properties - 'div { float: left; /* @noflip */ text-align: left; }', - 'div { float: right; /* @noflip */ text-align: left; }' - ), - - // Guard against css3 stuff - array( - 'background-image: -moz-linear-gradient(#326cc1, #234e8c);' - ), - array( - 'background-image: -webkit-gradient(linear, 100% 0%, 0% 0%, from(#666666), to(#ffffff));' - ), - - // CSS syntax / white-space variations - // spaces, no spaces, tabs, new lines, omitting semi-colons - array( - ".foo { left: 0; }", - ".foo { right: 0; }" - ), - array( - ".foo{ left: 0; }", - ".foo{ right: 0; }" - ), - array( - ".foo{ left: 0 }", - ".foo{ right: 0 }" - ), - array( - ".foo{left:0 }", - ".foo{right:0 }" - ), - array( - ".foo{left:0}", - ".foo{right:0}" - ), - array( - ".foo { left : 0 ; }", - ".foo { right : 0 ; }" - ), - array( - ".foo\n { left : 0 ; }", - ".foo\n { right : 0 ; }" - ), - array( - ".foo\n { \nleft : 0 ; }", - ".foo\n { \nright : 0 ; }" - ), - array( - ".foo\n { \n left : 0 ; }", - ".foo\n { \n right : 0 ; }" - ), - array( - ".foo\n { \n left\n : 0; }", - ".foo\n { \n right\n : 0; }" - ), - array( - ".foo \n { \n left\n : 0; }", - ".foo \n { \n right\n : 0; }" - ), - array( - ".foo\n{\nleft\n:\n0;}", - ".foo\n{\nright\n:\n0;}" - ), - array( - ".foo\n.bar {\n\tleft: 0;\n}", - ".foo\n.bar {\n\tright: 0;\n}" - ), - array( - ".foo\t{\tleft\t:\t0;}", - ".foo\t{\tright\t:\t0;}" - ), - ); - } - - /** - * These cases are tested in one way only (format: actual, expected, msg). - * If both ways can be tested, either put both versions in here or move - * it to provideTransformCases(). - */ - function provideTransformAdvancedCases() { - $bgPairs = array( - # [ - _ . ] <-> [ left right ltr rtl ] - 'foo.jpg' => 'foo.jpg', - 'left.jpg' => 'right.jpg', - 'ltr.jpg' => 'rtl.jpg', - - 'foo-left.png' => 'foo-right.png', - 'foo_left.png' => 'foo_right.png', - 'foo.left.png' => 'foo.right.png', - - 'foo-ltr.png' => 'foo-rtl.png', - 'foo_ltr.png' => 'foo_rtl.png', - 'foo.ltr.png' => 'foo.rtl.png', - - 'left-foo.png' => 'right-foo.png', - 'left_foo.png' => 'right_foo.png', - 'left.foo.png' => 'right.foo.png', - - 'ltr-foo.png' => 'rtl-foo.png', - 'ltr_foo.png' => 'rtl_foo.png', - 'ltr.foo.png' => 'rtl.foo.png', - - 'foo-ltr-left.gif' => 'foo-rtl-right.gif', - 'foo_ltr_left.gif' => 'foo_rtl_right.gif', - 'foo.ltr.left.gif' => 'foo.rtl.right.gif', - 'foo-ltr_left.gif' => 'foo-rtl_right.gif', - 'foo_ltr.left.gif' => 'foo_rtl.right.gif', - ); - $provider = array(); - foreach ( $bgPairs as $left => $right ) { - # By default '-rtl' and '-left' etc. are not touched, - # Only when the appropiate parameter is set. - $provider[] = array( - ".foo { background: url(images/$left); }", - ".foo { background: url(images/$left); }" - ); - $provider[] = array( - ".foo { background: url(images/$right); }", - ".foo { background: url(images/$right); }" - ); - $provider[] = array( - ".foo { background: url(images/$left); }", - ".foo { background: url(images/$right); }", - array( - 'swapLtrRtlInURL' => true, - 'swapLeftRightInURL' => true, - ) - ); - $provider[] = array( - ".foo { background: url(images/$right); }", - ".foo { background: url(images/$left); }", - array( - 'swapLtrRtlInURL' => true, - 'swapLeftRightInURL' => true, - ) - ); - } - - return $provider; - } - - /** - * Cases that are currently failing, but - * should be looked at in the future as enhancements and/or bug fix - */ - function provideTransformBrokenCases() { - return array( - // Guard against partial keys - array( - '.foo { leftxx: 0; }', - '.foo { leftxx: 0; }' - ), - array( - '.foo { rightxx: 0; }', - '.foo { rightxx: 0; }' - ), - - // Guard against selectors that look flippable - array( - # - 'foo-left-x[attr="x"] { width: 0; }', - 'foo-left-x[attr="x"] { width: 0; }' - ), - array( - #
- '.foo[data-left="x"] { width: 0; }', - '.foo[data-left="x"] { width: 0; }' - ), - ); - } -} diff --git a/tests/phpunit/includes/libs/CSSMinTest.php b/tests/phpunit/includes/libs/CSSMinTest.php deleted file mode 100644 index a3827756..00000000 --- a/tests/phpunit/includes/libs/CSSMinTest.php +++ /dev/null @@ -1,142 +0,0 @@ -oldServer = $wgServer; - $this->oldCanServer = $wgCanonicalServer; - $wgServer = $wgCanonicalServer = 'http://wiki.example.org'; - } - - function tearDown() { - // Restore $wgServer and $wgCanonicalServer - global $wgServer, $wgCanonicalServer; - $wgServer = $this->oldServer; - $wgCanonicalServer = $this->oldCanServer; - - parent::tearDown(); - } - - /** - * @dataProvider provideMinifyCases - */ - function testMinify( $code, $expectedOutput ) { - $minified = CSSMin::minify( $code ); - - $this->assertEquals( $expectedOutput, $minified, 'Minified output should be in the form expected.' ); - } - - function provideMinifyCases() { - return array( - // Whitespace - array( "\r\t\f \v\n\r", "" ), - array( "foo, bar {\n\tprop: value;\n}", "foo,bar{prop:value}" ), - - // Loose comments - array( "/* foo */", "" ), - array( "/*******\n foo\n *******/", "" ), - array( "/*!\n foo\n */", "" ), - - // Inline comments in various different places - array( "/* comment */foo, bar {\n\tprop: value;\n}", "foo,bar{prop:value}" ), - array( "foo/* comment */, bar {\n\tprop: value;\n}", "foo,bar{prop:value}" ), - array( "foo,/* comment */ bar {\n\tprop: value;\n}", "foo,bar{prop:value}" ), - array( "foo, bar/* comment */ {\n\tprop: value;\n}", "foo,bar{prop:value}" ), - array( "foo, bar {\n\t/* comment */prop: value;\n}", "foo,bar{prop:value}" ), - array( "foo, bar {\n\tprop: /* comment */value;\n}", "foo,bar{prop:value}" ), - array( "foo, bar {\n\tprop: value /* comment */;\n}", "foo,bar{prop:value }" ), - array( "foo, bar {\n\tprop: value; /* comment */\n}", "foo,bar{prop:value; }" ), - - // Keep track of things that aren't as minified as much as they - // could be (bug 35493) - array( 'foo { prop: value ;}', 'foo{prop:value }' ), - array( 'foo { prop : value; }', 'foo{prop :value}' ), - array( 'foo { prop: value ; }', 'foo{prop:value }' ), - array( 'foo { font-family: "foo" , "bar"; }', 'foo{font-family:"foo" ,"bar"}' ), - array( "foo { src:\n\turl('foo') ,\n\turl('bar') ; }", "foo{src:url('foo') ,url('bar') }" ), - - // Interesting cases with string values - // - Double quotes, single quotes - array( 'foo { content: ""; }', 'foo{content:""}' ), - array( "foo { content: ''; }", "foo{content:''}" ), - array( 'foo { content: "\'"; }', 'foo{content:"\'"}' ), - array( "foo { content: '\"'; }", "foo{content:'\"'}" ), - // - Whitespace in string values - array( 'foo { content: " "; }', 'foo{content:" "}' ), - ); - } - - /** - * @dataProvider provideRemapCases - */ - function testRemap( $message, $params, $expectedOutput ) { - $remapped = call_user_func_array( 'CSSMin::remap', $params ); - - $messageAdd = " Case: $message"; - $this->assertEquals( $expectedOutput, $remapped, 'CSSMin::remap should return the expected url form.' . $messageAdd ); - } - - function provideRemapCases() { - // Parameter signature: - // CSSMin::remap( $code, $local, $remote, $embedData = true ) - return array( - array( - 'Simple case', - array( 'foo { prop: url(bar.png); }', false, 'http://example.org', false ), - 'foo { prop: url(http://example.org/bar.png); }', - ), - array( - 'Without trailing slash', - array( 'foo { prop: url(../bar.png); }', false, 'http://example.org/quux', false ), - 'foo { prop: url(http://example.org/quux/../bar.png); }', - ), - array( - 'With trailing slash on remote (bug 27052)', - array( 'foo { prop: url(../bar.png); }', false, 'http://example.org/quux/', false ), - 'foo { prop: url(http://example.org/quux/../bar.png); }', - ), - array( - 'Guard against stripping double slashes from query', - array( 'foo { prop: url(bar.png?corge=//grault); }', false, 'http://example.org/quux/', false ), - 'foo { prop: url(http://example.org/quux/bar.png?corge=//grault); }', - ), - array( - 'Expand absolute paths', - array( 'foo { prop: url(/w/skin/images/bar.png); }', false, 'http://example.org/quux', false ), - 'foo { prop: url(http://wiki.example.org/w/skin/images/bar.png); }', - ), - ); - } - - /** - * Seperated because they are currently broken (bug 35492) - * - * @group Broken - * @dataProvider provideStringCases - */ - function testMinifyWithCSSStringValues( $code, $expectedOutput ) { - $this->testMinifyOutput( $code, $expectedOutput ); - } - - function provideStringCases() { - return array( - // String values should be respected - // - More than one space in a string value - array( 'foo { content: " "; }', 'foo{content:" "}' ), - // - Using a tab in a string value (turns into a space) - array( "foo { content: '\t'; }", "foo{content:'\t'}" ), - // - Using css-like syntax in string values - array( 'foo::after { content: "{;}"; position: absolute; }', 'foo::after{content:"{;}";position:absolute}' ), - ); - } -} diff --git a/tests/phpunit/includes/libs/GenericArrayObjectTest.php b/tests/phpunit/includes/libs/GenericArrayObjectTest.php deleted file mode 100644 index 70fce111..00000000 --- a/tests/phpunit/includes/libs/GenericArrayObjectTest.php +++ /dev/null @@ -1,245 +0,0 @@ - - */ -abstract class GenericArrayObjectTest extends MediaWikiTestCase { - - /** - * Returns objects that can serve as elements in the concrete GenericArrayObject deriving class being tested. - * - * @since 1.20 - * - * @return array - */ - public abstract function elementInstancesProvider(); - - /** - * Returns the name of the concrete class being tested. - * - * @since 1.20 - * - * @return string - */ - public abstract function getInstanceClass(); - - /** - * Provides instances of the concrete class being tested. - * - * @since 1.20 - * - * @return array - */ - public function instanceProvider() { - $instances = array(); - - foreach ( $this->elementInstancesProvider() as $elementInstances ) { - $instances[] = $this->getNew( $elementInstances ); - } - - return $this->arrayWrap( $instances ); - } - - /** - * @since 1.20 - * - * @param array $elements - * - * @return GenericArrayObject - */ - protected function getNew( array $elements = array() ) { - $class = $this->getInstanceClass(); - return new $class( $elements ); - } - - /** - * @dataProvider elementInstancesProvider - * - * @since 1.20 - * - * @param array $elements - */ - public function testConstructor( array $elements ) { - $arrayObject = $this->getNew( $elements ); - - $this->assertEquals( count( $elements ), $arrayObject->count() ); - } - - /** - * @dataProvider elementInstancesProvider - * - * @since 1.20 - * - * @param array $elements - */ - public function testIsEmpty( array $elements ) { - $arrayObject = $this->getNew( $elements ); - - $this->assertEquals( $elements === array(), $arrayObject->isEmpty() ); - } - - /** - * @dataProvider instanceProvider - * - * @since 1.20 - * - * @param GenericArrayObject $list - */ - public function testUnset( GenericArrayObject $list ) { - if ( !$list->isEmpty() ) { - $offset = $list->getIterator()->key(); - $count = $list->count(); - $list->offsetUnset( $offset ); - $this->assertEquals( $count - 1, $list->count() ); - } - - if ( !$list->isEmpty() ) { - $offset = $list->getIterator()->key(); - $count = $list->count(); - unset( $list[$offset] ); - $this->assertEquals( $count - 1, $list->count() ); - } - - $exception = null; - try { $list->offsetUnset( 'sdfsedtgsrdysftu' ); } catch ( \Exception $exception ){} - $this->assertInstanceOf( '\Exception', $exception ); - } - - /** - * @dataProvider elementInstancesProvider - * - * @since 1.20 - * - * @param array $elements - */ - public function testAppend( array $elements ) { - $list = $this->getNew(); - - $listSize = count( $elements ); - - foreach ( $elements as $element ) { - $list->append( $element ); - } - - $this->assertEquals( $listSize, $list->count() ); - - $list = $this->getNew(); - - foreach ( $elements as $element ) { - $list[] = $element; - } - - $this->assertEquals( $listSize, $list->count() ); - - $this->checkTypeChecks( function( GenericArrayObject $list, $element ) { - $list->append( $element ); - } ); - } - - /** - * @since 1.20 - * - * @param callback $function - */ - protected function checkTypeChecks( $function ) { - $excption = null; - $list = $this->getNew(); - - $elementClass = $list->getObjectType(); - - foreach ( array( 42, 'foo', array(), new \stdClass(), 4.2 ) as $element ) { - $validValid = $element instanceof $elementClass; - - try{ - call_user_func( $function, $list, $element ); - $valid = true; - } - catch ( InvalidArgumentException $exception ) { - $valid = false; - } - - $this->assertEquals( - $validValid, - $valid, - 'Object of invalid type got successfully added to a GenericArrayObject' - ); - } - } - - /** - * @dataProvider elementInstancesProvider - * - * @since 1.20 - * - * @param array $elements - */ - public function testOffsetSet( array $elements ) { - if ( $elements === array() ) { - $this->assertTrue( true ); - return; - } - - $list = $this->getNew(); - - $element = reset( $elements ); - $list->offsetSet( 42, $element ); - $this->assertEquals( $element, $list->offsetGet( 42 ) ); - - $list = $this->getNew(); - - $element = reset( $elements ); - $list['oHai'] = $element; - $this->assertEquals( $element, $list['oHai'] ); - - $list = $this->getNew(); - - $element = reset( $elements ); - $list->offsetSet( 9001, $element ); - $this->assertEquals( $element, $list[9001] ); - - $list = $this->getNew(); - - $element = reset( $elements ); - $list->offsetSet( null, $element ); - $this->assertEquals( $element, $list[0] ); - - $list = $this->getNew(); - $offset = 0; - - foreach ( $elements as $element ) { - $list->offsetSet( null, $element ); - $this->assertEquals( $element, $list[$offset++] ); - } - - $this->assertEquals( count( $elements ), $list->count() ); - - $this->checkTypeChecks( function( GenericArrayObject $list, $element ) { - $list->offsetSet( mt_rand(), $element ); - } ); - } - -} diff --git a/tests/phpunit/includes/libs/IEUrlExtensionTest.php b/tests/phpunit/includes/libs/IEUrlExtensionTest.php deleted file mode 100644 index c6270e90..00000000 --- a/tests/phpunit/includes/libs/IEUrlExtensionTest.php +++ /dev/null @@ -1,118 +0,0 @@ -assertEquals( - 'y', - IEUrlExtension::findIE6Extension( 'x.y' ), - 'Simple extension' - ); - } - - function testSimpleNoExt() { - $this->assertEquals( - '', - IEUrlExtension::findIE6Extension( 'x' ), - 'No extension' - ); - } - - function testEmpty() { - $this->assertEquals( - '', - IEUrlExtension::findIE6Extension( '' ), - 'Empty string' - ); - } - - function testQuestionMark() { - $this->assertEquals( - '', - IEUrlExtension::findIE6Extension( '?' ), - 'Question mark only' - ); - } - - function testExtQuestionMark() { - $this->assertEquals( - 'x', - IEUrlExtension::findIE6Extension( '.x?' ), - 'Extension then question mark' - ); - } - - function testQuestionMarkExt() { - $this->assertEquals( - 'x', - IEUrlExtension::findIE6Extension( '?.x' ), - 'Question mark then extension' - ); - } - - function testInvalidChar() { - $this->assertEquals( - '', - IEUrlExtension::findIE6Extension( '.x*' ), - 'Extension with invalid character' - ); - } - - function testInvalidCharThenExtension() { - $this->assertEquals( - 'x', - IEUrlExtension::findIE6Extension( '*.x' ), - 'Invalid character followed by an extension' - ); - } - - function testMultipleQuestionMarks() { - $this->assertEquals( - 'c', - IEUrlExtension::findIE6Extension( 'a?b?.c?.d?e?f' ), - 'Multiple question marks' - ); - } - - function testExeException() { - $this->assertEquals( - 'd', - IEUrlExtension::findIE6Extension( 'a?b?.exe?.d?.e' ), - '.exe exception' - ); - } - - function testExeException2() { - $this->assertEquals( - 'exe', - IEUrlExtension::findIE6Extension( 'a?b?.exe' ), - '.exe exception 2' - ); - } - - function testHash() { - $this->assertEquals( - '', - IEUrlExtension::findIE6Extension( 'a#b.c' ), - 'Hash character preceding extension' - ); - } - - function testHash2() { - $this->assertEquals( - '', - IEUrlExtension::findIE6Extension( 'a?#b.c' ), - 'Hash character preceding extension 2' - ); - } - - function testDotAtEnd() { - $this->assertEquals( - '', - IEUrlExtension::findIE6Extension( '.' ), - 'Dot at end of string' - ); - } -} diff --git a/tests/phpunit/includes/libs/JavaScriptMinifierTest.php b/tests/phpunit/includes/libs/JavaScriptMinifierTest.php deleted file mode 100644 index f121b018..00000000 --- a/tests/phpunit/includes/libs/JavaScriptMinifierTest.php +++ /dev/null @@ -1,170 +0,0 @@ - bar", "" ), - array( "--> Foo", "" ), - array( "x --> y", "x-->y" ), - - // Semicolon insertion - array( "(function(){return\nx;})", "(function(){return\nx;})" ), - array( "throw\nx;", "throw\nx;" ), - array( "while(p){continue\nx;}", "while(p){continue\nx;}" ), - array( "while(p){break\nx;}", "while(p){break\nx;}" ), - array( "var\nx;", "var x;" ), - array( "x\ny;", "x\ny;" ), - array( "x\n++y;", "x\n++y;" ), - array( "x\n!y;", "x\n!y;" ), - array( "x\n{y}", "x\n{y}" ), - array( "x\n+y;", "x+y;" ), - array( "x\n(y);", "x(y);" ), - array( "5.\nx;", "5.\nx;" ), - array( "0xFF.\nx;", "0xFF.x;" ), - array( "5.3.\nx;", "5.3.x;" ), - - // Semicolon insertion between an expression having an inline - // comment after it, and a statement on the next line (bug 27046). - array( "var a = this //foo bar \n for ( b = 0; c < d; b++ ) {}", "var a=this\nfor(b=0;cparse( $minified, 'minify-test.js', 1 ); - - $this->assertEquals( $expectedOutput, $minified, "Minified output should be in the form expected." ); - } - - function provideBug32548() { - return array( - array( - // This one gets interpreted all together by the prior code; - // no break at the 'E' happens. - '1.23456789E55', - ), - array( - // This one breaks under the bad code; splits between 'E' and '+' - '1.23456789E+5', - ), - array( - // This one breaks under the bad code; splits between 'E' and '-' - '1.23456789E-5', - ), - ); - } - - /** - * @dataProvider provideBug32548 - */ - function testBug32548Exponent( $num ) { - // Long line breaking was being incorrectly done between the base and - // exponent part of a number, causing a syntax error. The line should - // instead break at the start of the number. - $prefix = 'var longVarName' . str_repeat( '_', 973 ) . '='; - $suffix = ',shortVarName=0;'; - - $input = $prefix . $num . $suffix; - $expected = $prefix . "\n" . $num . $suffix; - - $minified = JavaScriptMinifier::minify( $input ); - - $this->assertEquals( $expected, $minified, "Line breaks must not occur in middle of exponent"); - } -} diff --git a/tests/phpunit/includes/media/BitmapMetadataHandlerTest.php b/tests/phpunit/includes/media/BitmapMetadataHandlerTest.php deleted file mode 100644 index 88f87ef9..00000000 --- a/tests/phpunit/includes/media/BitmapMetadataHandlerTest.php +++ /dev/null @@ -1,146 +0,0 @@ -filePath = __DIR__ . '/../../data/media/'; - } - - /** - * Test if having conflicting metadata values from different - * types of metadata, that the right one takes precedence. - * - * Basically the file has IPTC and XMP metadata, the - * IPTC should override the XMP, except for the multilingual - * translation (to en) where XMP should win. - */ - public function testMultilingualCascade() { - if ( !wfDl( 'exif' ) ) { - $this->markTestSkipped( "This test needs the exif extension." ); - } - if ( !wfDl( 'xml' ) ) { - $this->markTestSkipped( "This test needs the xml extension." ); - } - global $wgShowEXIF; - $oldExif = $wgShowEXIF; - $wgShowEXIF = true; - - $meta = BitmapMetadataHandler::Jpeg( $this->filePath . - '/Xmp-exif-multilingual_test.jpg' ); - - $expected = array( - 'x-default' => 'right(iptc)', - 'en' => 'right translation', - '_type' => 'lang' - ); - - $this->assertArrayHasKey( 'ImageDescription', $meta, - 'Did not extract any ImageDescription info?!' ); - - $this->assertEquals( $expected, $meta['ImageDescription'] ); - - $wgShowEXIF = $oldExif; - } - - /** - * Test for jpeg comments are being handled by - * BitmapMetadataHandler correctly. - * - * There's more extensive tests of comment extraction in - * JpegMetadataExtractorTests.php - */ - public function testJpegComment() { - $meta = BitmapMetadataHandler::Jpeg( $this->filePath . - 'jpeg-comment-utf.jpg' ); - - $this->assertEquals( 'UTF-8 JPEG Comment — ¼', - $meta['JPEGFileComment'][0] ); - } - - /** - * Make sure a bad iptc block doesn't stop the other metadata - * from being extracted. - */ - public function testBadIPTC() { - $meta = BitmapMetadataHandler::Jpeg( $this->filePath . - 'iptc-invalid-psir.jpg' ); - $this->assertEquals( 'Created with GIMP', $meta['JPEGFileComment'][0] ); - } - - public function testIPTCDates() { - $meta = BitmapMetadataHandler::Jpeg( $this->filePath . - 'iptc-timetest.jpg' ); - - $this->assertEquals( '2020:07:14 01:36:05', $meta['DateTimeDigitized'] ); - $this->assertEquals( '1997:03:02 00:01:02', $meta['DateTimeOriginal'] ); - } - /** - * File has an invalid time (+ one valid but really weird time) - * that shouldn't be included - */ - public function testIPTCDatesInvalid() { - $meta = BitmapMetadataHandler::Jpeg( $this->filePath . - 'iptc-timetest-invalid.jpg' ); - - $this->assertEquals( '1845:03:02 00:01:02', $meta['DateTimeOriginal'] ); - $this->assertFalse( isset( $meta['DateTimeDigitized'] ) ); - } - - /** - * XMP data should take priority over iptc data - * when hash has been updated, but not when - * the hash is wrong. - */ - public function testMerging() { - $merger = new BitmapMetadataHandler(); - $merger->addMetadata( array( 'foo' => 'xmp' ), 'xmp-general' ); - $merger->addMetadata( array( 'bar' => 'xmp' ), 'xmp-general' ); - $merger->addMetadata( array( 'baz' => 'xmp' ), 'xmp-general' ); - $merger->addMetadata( array( 'fred' => 'xmp' ), 'xmp-general' ); - $merger->addMetadata( array( 'foo' => 'iptc (hash)' ), 'iptc-good-hash' ); - $merger->addMetadata( array( 'bar' => 'iptc (bad hash)' ), 'iptc-bad-hash' ); - $merger->addMetadata( array( 'baz' => 'iptc (bad hash)' ), 'iptc-bad-hash' ); - $merger->addMetadata( array( 'fred' => 'iptc (no hash)' ), 'iptc-no-hash' ); - $merger->addMetadata( array( 'baz' => 'exif' ), 'exif' ); - - $actual = $merger->getMetadataArray(); - $expected = array( - 'foo' => 'xmp', - 'bar' => 'iptc (bad hash)', - 'baz' => 'exif', - 'fred' => 'xmp', - ); - $this->assertEquals( $expected, $actual ); - } - - public function testPNGXMP() { - if ( !wfDl( 'xml' ) ) { - $this->markTestSkipped( "This test needs the xml extension." ); - } - $handler = new BitmapMetadataHandler(); - $result = $handler->png( $this->filePath . 'xmp.png' ); - $expected = array ( - 'frameCount' => 0, - 'loopCount' => 1, - 'duration' => 0, - 'bitDepth' => 1, - 'colorType' => 'index-coloured', - 'metadata' => array ( - 'SerialNumber' => '123456789', - '_MW_PNG_VERSION' => 1, - ), - ); - $this->assertEquals( $expected, $result ); - } - public function testPNGNative() { - $handler = new BitmapMetadataHandler(); - $result = $handler->png( $this->filePath . 'Png-native-test.png' ); - $expected = 'http://example.com/url'; - $this->assertEquals( $expected, $result['metadata']['Identifier']['x-default'] ); - } - public function testTiffByteOrder() { - $handler = new BitmapMetadataHandler(); - $res = $handler->getTiffByteOrder( $this->filePath . 'test.tiff' ); - $this->assertEquals( 'LE', $res ); - } - -} diff --git a/tests/phpunit/includes/media/BitmapScalingTest.php b/tests/phpunit/includes/media/BitmapScalingTest.php deleted file mode 100644 index 11d9dc47..00000000 --- a/tests/phpunit/includes/media/BitmapScalingTest.php +++ /dev/null @@ -1,151 +0,0 @@ -oldMaxImageArea = $wgMaxImageArea; - $this->oldCustomConvertCommand = $wgCustomConvertCommand; - $wgMaxImageArea = 1.25e7; // 3500x3500 - $wgCustomConvertCommand = 'dummy'; // Set so that we don't get client side rendering - } - function tearDown() { - global $wgMaxImageArea, $wgCustomConvertCommand; - $wgMaxImageArea = $this->oldMaxImageArea; - $wgCustomConvertCommand = $this->oldCustomConvertCommand; - } - /** - * @dataProvider provideNormaliseParams - */ - function testNormaliseParams( $fileDimensions, $expectedParams, $params, $msg ) { - $file = new FakeDimensionFile( $fileDimensions ); - $handler = new BitmapHandler; - $valid = $handler->normaliseParams( $file, $params ); - $this->assertTrue( $valid ); - $this->assertEquals( $expectedParams, $params, $msg ); - } - - function provideNormaliseParams() { - return array( - /* Regular resize operations */ - array( - array( 1024, 768 ), - array( - 'width' => 512, 'height' => 384, - 'physicalWidth' => 512, 'physicalHeight' => 384, - 'page' => 1, - ), - array( 'width' => 512 ), - 'Resizing with width set', - ), - array( - array( 1024, 768 ), - array( - 'width' => 512, 'height' => 384, - 'physicalWidth' => 512, 'physicalHeight' => 384, - 'page' => 1, - ), - array( 'width' => 512, 'height' => 768 ), - 'Resizing with height set too high', - ), - array( - array( 1024, 768 ), - array( - 'width' => 512, 'height' => 384, - 'physicalWidth' => 512, 'physicalHeight' => 384, - 'page' => 1, - ), - array( 'width' => 1024, 'height' => 384 ), - 'Resizing with height set', - ), - - /* Very tall images */ - array( - array( 1000, 100 ), - array( - 'width' => 5, 'height' => 1, - 'physicalWidth' => 5, 'physicalHeight' => 1, - 'page' => 1, - ), - array( 'width' => 5 ), - 'Very wide image', - ), - - array( - array( 100, 1000 ), - array( - 'width' => 1, 'height' => 10, - 'physicalWidth' => 1, 'physicalHeight' => 10, - 'page' => 1, - ), - array( 'width' => 1 ), - 'Very high image', - ), - array( - array( 100, 1000 ), - array( - 'width' => 1, 'height' => 5, - 'physicalWidth' => 1, 'physicalHeight' => 10, - 'page' => 1, - ), - array( 'width' => 10, 'height' => 5 ), - 'Very high image with height set', - ), - /* Max image area */ - array( - array( 4000, 4000 ), - array( - 'width' => 5000, 'height' => 5000, - 'physicalWidth' => 4000, 'physicalHeight' => 4000, - 'page' => 1, - ), - array( 'width' => 5000 ), - 'Bigger than max image size but doesn\'t need scaling', - ), - ); - } - function testTooBigImage() { - $file = new FakeDimensionFile( array( 4000, 4000 ) ); - $handler = new BitmapHandler; - $params = array( 'width' => '3700' ); // Still bigger than max size. - $this->assertEquals( 'TransformParameterError', - get_class( $handler->doTransform( $file, 'dummy path', '', $params ) ) ); - } - function testTooBigMustRenderImage() { - $file = new FakeDimensionFile( array( 4000, 4000 ) ); - $file->mustRender = true; - $handler = new BitmapHandler; - $params = array( 'width' => '5000' ); // Still bigger than max size. - $this->assertEquals( 'TransformParameterError', - get_class( $handler->doTransform( $file, 'dummy path', '', $params ) ) ); - } - - function testImageArea() { - $file = new FakeDimensionFile( array( 7, 9 ) ); - $handler = new BitmapHandler; - $this->assertEquals( 63, $handler->getImageArea( $file ) ); - } -} - -class FakeDimensionFile extends File { - public $mustRender = false; - - public function __construct( $dimensions ) { - parent::__construct( Title::makeTitle( NS_FILE, 'Test' ), - new NullRepo( null ) ); - - $this->dimensions = $dimensions; - } - public function getWidth( $page = 1 ) { - return $this->dimensions[0]; - } - public function getHeight( $page = 1 ) { - return $this->dimensions[1]; - } - public function mustRender() { - return $this->mustRender; - } - public function getPath() { - return ''; - } -} diff --git a/tests/phpunit/includes/media/ExifBitmapTest.php b/tests/phpunit/includes/media/ExifBitmapTest.php deleted file mode 100644 index b2f6b7ba..00000000 --- a/tests/phpunit/includes/media/ExifBitmapTest.php +++ /dev/null @@ -1,100 +0,0 @@ -showExif = $wgShowEXIF; - $wgShowEXIF = true; - $this->handler = new ExifBitmapHandler; - if ( !wfDl( 'exif' ) ) { - $this->markTestSkipped( "This test needs the exif extension." ); - } - } - - public function tearDown() { - global $wgShowEXIF; - $wgShowEXIF = $this->showExif; - } - - public function testIsOldBroken() { - $res = $this->handler->isMetadataValid( null, ExifBitmapHandler::OLD_BROKEN_FILE ); - $this->assertEquals( ExifBitmapHandler::METADATA_COMPATIBLE, $res ); - } - public function testIsBrokenFile() { - $res = $this->handler->isMetadataValid( null, ExifBitmapHandler::BROKEN_FILE ); - $this->assertEquals( ExifBitmapHandler::METADATA_GOOD, $res ); - } - public function testIsInvalid() { - $res = $this->handler->isMetadataValid( null, 'Something Invalid Here.' ); - $this->assertEquals( ExifBitmapHandler::METADATA_BAD, $res ); - } - public function testGoodMetadata() { - $meta = 'a:16:{s:10:"ImageWidth";i:20;s:11:"ImageLength";i:20;s:13:"BitsPerSample";a:3:{i:0;i:8;i:1;i:8;i:2;i:8;}s:11:"Compression";i:5;s:25:"PhotometricInterpretation";i:2;s:16:"ImageDescription";s:17:"Created with GIMP";s:12:"StripOffsets";i:8;s:11:"Orientation";i:1;s:15:"SamplesPerPixel";i:3;s:12:"RowsPerStrip";i:64;s:15:"StripByteCounts";i:238;s:11:"XResolution";s:19:"1207959552/16777216";s:11:"YResolution";s:19:"1207959552/16777216";s:19:"PlanarConfiguration";i:1;s:14:"ResolutionUnit";i:2;s:22:"MEDIAWIKI_EXIF_VERSION";i:2;}'; - $res = $this->handler->isMetadataValid( null, $meta ); - $this->assertEquals( ExifBitmapHandler::METADATA_GOOD, $res ); - } - public function testIsOldGood() { - $meta = 'a:16:{s:10:"ImageWidth";i:20;s:11:"ImageLength";i:20;s:13:"BitsPerSample";a:3:{i:0;i:8;i:1;i:8;i:2;i:8;}s:11:"Compression";i:5;s:25:"PhotometricInterpretation";i:2;s:16:"ImageDescription";s:17:"Created with GIMP";s:12:"StripOffsets";i:8;s:11:"Orientation";i:1;s:15:"SamplesPerPixel";i:3;s:12:"RowsPerStrip";i:64;s:15:"StripByteCounts";i:238;s:11:"XResolution";s:19:"1207959552/16777216";s:11:"YResolution";s:19:"1207959552/16777216";s:19:"PlanarConfiguration";i:1;s:14:"ResolutionUnit";i:2;s:22:"MEDIAWIKI_EXIF_VERSION";i:1;}'; - $res = $this->handler->isMetadataValid( null, $meta ); - $this->assertEquals( ExifBitmapHandler::METADATA_COMPATIBLE, $res ); - } - // Handle metadata from paged tiff handler (gotten via instant commons) - // gracefully. - public function testPagedTiffHandledGracefully() { - $meta = 'a:6:{s:9:"page_data";a:1:{i:1;a:5:{s:5:"width";i:643;s:6:"height";i:448;s:5:"alpha";s:4:"true";s:4:"page";i:1;s:6:"pixels";i:288064;}}s:10:"page_count";i:1;s:10:"first_page";i:1;s:9:"last_page";i:1;s:4:"exif";a:9:{s:10:"ImageWidth";i:643;s:11:"ImageLength";i:448;s:11:"Compression";i:5;s:25:"PhotometricInterpretation";i:2;s:11:"Orientation";i:1;s:15:"SamplesPerPixel";i:4;s:12:"RowsPerStrip";i:50;s:19:"PlanarConfiguration";i:1;s:22:"MEDIAWIKI_EXIF_VERSION";i:1;}s:21:"TIFF_METADATA_VERSION";s:3:"1.4";}'; - $res = $this->handler->isMetadataValid( null, $meta ); - $this->assertEquals( ExifBitmapHandler::METADATA_BAD, $res ); - } - - function testConvertMetadataLatest() { - $metadata = array( - 'foo' => array( 'First', 'Second', '_type' => 'ol' ), - 'MEDIAWIKI_EXIF_VERSION' => 2 - ); - $res = $this->handler->convertMetadataVersion( $metadata, 2 ); - $this->assertEquals( $metadata, $res ); - } - function testConvertMetadataToOld() { - $metadata = array( - 'foo' => array( 'First', 'Second', '_type' => 'ol' ), - 'bar' => array( 'First', 'Second', '_type' => 'ul' ), - 'baz' => array( 'First', 'Second' ), - 'fred' => 'Single', - 'MEDIAWIKI_EXIF_VERSION' => 2, - ); - $expected = array( - 'foo' => "\n#First\n#Second", - 'bar' => "\n*First\n*Second", - 'baz' => "\n*First\n*Second", - 'fred' => 'Single', - 'MEDIAWIKI_EXIF_VERSION' => 1, - ); - $res = $this->handler->convertMetadataVersion( $metadata, 1 ); - $this->assertEquals( $expected, $res ); - } - function testConvertMetadataSoftware() { - $metadata = array( - 'Software' => array( array('GIMP', '1.1' ) ), - 'MEDIAWIKI_EXIF_VERSION' => 2, - ); - $expected = array( - 'Software' => 'GIMP (Version 1.1)', - 'MEDIAWIKI_EXIF_VERSION' => 1, - ); - $res = $this->handler->convertMetadataVersion( $metadata, 1 ); - $this->assertEquals( $expected, $res ); - } - function testConvertMetadataSoftwareNormal() { - $metadata = array( - 'Software' => array( "GIMP 1.2", "vim" ), - 'MEDIAWIKI_EXIF_VERSION' => 2, - ); - $expected = array( - 'Software' => "\n*GIMP 1.2\n*vim", - 'MEDIAWIKI_EXIF_VERSION' => 1, - ); - $res = $this->handler->convertMetadataVersion( $metadata, 1 ); - $this->assertEquals( $expected, $res ); - } -} diff --git a/tests/phpunit/includes/media/ExifRotationTest.php b/tests/phpunit/includes/media/ExifRotationTest.php deleted file mode 100644 index 6af52dd1..00000000 --- a/tests/phpunit/includes/media/ExifRotationTest.php +++ /dev/null @@ -1,260 +0,0 @@ -handler = new BitmapHandler(); - $filePath = __DIR__ . '/../../data/media'; - - $tmpDir = $this->getNewTempDirectory(); - - $this->repo = new FSRepo( array( - 'name' => 'temp', - 'url' => 'http://localhost/thumbtest', - 'backend' => new FSFileBackend( array( - 'name' => 'localtesting', - 'lockManager' => 'nullLockManager', - 'containerPaths' => array( 'temp-thumb' => $tmpDir, 'data' => $filePath ) - ) ) - ) ); - if ( !wfDl( 'exif' ) ) { - $this->markTestSkipped( "This test needs the exif extension." ); - } - global $wgShowEXIF; - $this->show = $wgShowEXIF; - $wgShowEXIF = true; - - global $wgEnableAutoRotation; - $this->oldAuto = $wgEnableAutoRotation; - $wgEnableAutoRotation = true; - } - - public function tearDown() { - global $wgShowEXIF, $wgEnableAutoRotation; - $wgShowEXIF = $this->show; - $wgEnableAutoRotation = $this->oldAuto; - - parent::tearDown(); - } - - /** - * - * @dataProvider providerFiles - */ - function testMetadata( $name, $type, $info ) { - if ( !BitmapHandler::canRotate() ) { - $this->markTestSkipped( "This test needs a rasterizer that can auto-rotate." ); - } - $file = $this->dataFile( $name, $type ); - $this->assertEquals( $info['width'], $file->getWidth(), "$name: width check" ); - $this->assertEquals( $info['height'], $file->getHeight(), "$name: height check" ); - } - - /** - * - * @dataProvider providerFiles - */ - function testRotationRendering( $name, $type, $info, $thumbs ) { - if ( !BitmapHandler::canRotate() ) { - $this->markTestSkipped( "This test needs a rasterizer that can auto-rotate." ); - } - foreach( $thumbs as $size => $out ) { - if( preg_match('/^(\d+)px$/', $size, $matches ) ) { - $params = array( - 'width' => $matches[1], - ); - } elseif ( preg_match( '/^(\d+)x(\d+)px$/', $size, $matches ) ) { - $params = array( - 'width' => $matches[1], - 'height' => $matches[2] - ); - } else { - throw new MWException('bogus test data format ' . $size); - } - - $file = $this->dataFile( $name, $type ); - $thumb = $file->transform( $params, File::RENDER_NOW | File::RENDER_FORCE ); - - $this->assertEquals( $out[0], $thumb->getWidth(), "$name: thumb reported width check for $size" ); - $this->assertEquals( $out[1], $thumb->getHeight(), "$name: thumb reported height check for $size" ); - - $gis = getimagesize( $thumb->getLocalCopyPath() ); - if ($out[0] > $info['width']) { - // Physical image won't be scaled bigger than the original. - $this->assertEquals( $info['width'], $gis[0], "$name: thumb actual width check for $size"); - $this->assertEquals( $info['height'], $gis[1], "$name: thumb actual height check for $size"); - } else { - $this->assertEquals( $out[0], $gis[0], "$name: thumb actual width check for $size"); - $this->assertEquals( $out[1], $gis[1], "$name: thumb actual height check for $size"); - } - } - } - - private function dataFile( $name, $type ) { - return new UnregisteredLocalFile( false, $this->repo, - "mwstore://localtesting/data/$name", $type ); - } - - function providerFiles() { - return array( - array( - 'landscape-plain.jpg', - 'image/jpeg', - array( - 'width' => 1024, - 'height' => 768, - ), - array( - '800x600px' => array( 800, 600 ), - '9999x800px' => array( 1067, 800 ), - '800px' => array( 800, 600 ), - '600px' => array( 600, 450 ), - ) - ), - array( - 'portrait-rotated.jpg', - 'image/jpeg', - array( - 'width' => 768, // as rotated - 'height' => 1024, // as rotated - ), - array( - '800x600px' => array( 450, 600 ), - '9999x800px' => array( 600, 800 ), - '800px' => array( 800, 1067 ), - '600px' => array( 600, 800 ), - ) - ) - ); - } - - /** - * Same as before, but with auto-rotation disabled. - * @dataProvider providerFilesNoAutoRotate - */ - function testMetadataNoAutoRotate( $name, $type, $info ) { - global $wgEnableAutoRotation; - $wgEnableAutoRotation = false; - - $file = $this->dataFile( $name, $type ); - $this->assertEquals( $info['width'], $file->getWidth(), "$name: width check" ); - $this->assertEquals( $info['height'], $file->getHeight(), "$name: height check" ); - - $wgEnableAutoRotation = true; - } - - /** - * - * @dataProvider providerFilesNoAutoRotate - */ - function testRotationRenderingNoAutoRotate( $name, $type, $info, $thumbs ) { - global $wgEnableAutoRotation; - $wgEnableAutoRotation = false; - - foreach( $thumbs as $size => $out ) { - if( preg_match('/^(\d+)px$/', $size, $matches ) ) { - $params = array( - 'width' => $matches[1], - ); - } elseif ( preg_match( '/^(\d+)x(\d+)px$/', $size, $matches ) ) { - $params = array( - 'width' => $matches[1], - 'height' => $matches[2] - ); - } else { - throw new MWException('bogus test data format ' . $size); - } - - $file = $this->dataFile( $name, $type ); - $thumb = $file->transform( $params, File::RENDER_NOW | File::RENDER_FORCE ); - - $this->assertEquals( $out[0], $thumb->getWidth(), "$name: thumb reported width check for $size" ); - $this->assertEquals( $out[1], $thumb->getHeight(), "$name: thumb reported height check for $size" ); - - $gis = getimagesize( $thumb->getLocalCopyPath() ); - if ($out[0] > $info['width']) { - // Physical image won't be scaled bigger than the original. - $this->assertEquals( $info['width'], $gis[0], "$name: thumb actual width check for $size"); - $this->assertEquals( $info['height'], $gis[1], "$name: thumb actual height check for $size"); - } else { - $this->assertEquals( $out[0], $gis[0], "$name: thumb actual width check for $size"); - $this->assertEquals( $out[1], $gis[1], "$name: thumb actual height check for $size"); - } - } - $wgEnableAutoRotation = true; - } - - function providerFilesNoAutoRotate() { - return array( - array( - 'landscape-plain.jpg', - 'image/jpeg', - array( - 'width' => 1024, - 'height' => 768, - ), - array( - '800x600px' => array( 800, 600 ), - '9999x800px' => array( 1067, 800 ), - '800px' => array( 800, 600 ), - '600px' => array( 600, 450 ), - ) - ), - array( - 'portrait-rotated.jpg', - 'image/jpeg', - array( - 'width' => 1024, // since not rotated - 'height' => 768, // since not rotated - ), - array( - '800x600px' => array( 800, 600 ), - '9999x800px' => array( 1067, 800 ), - '800px' => array( 800, 600 ), - '600px' => array( 600, 450 ), - ) - ) - ); - } - - - const TEST_WIDTH = 100; - const TEST_HEIGHT = 200; - - /** - * @dataProvider provideBitmapExtractPreRotationDimensions - */ - function testBitmapExtractPreRotationDimensions( $rotation, $expected ) { - $result = $this->handler->extractPreRotationDimensions( array( - 'physicalWidth' => self::TEST_WIDTH, - 'physicalHeight' => self::TEST_HEIGHT, - ), $rotation ); - $this->assertEquals( $expected, $result ); - } - - function provideBitmapExtractPreRotationDimensions() { - return array( - array( - 0, - array( self::TEST_WIDTH, self::TEST_HEIGHT ) - ), - array( - 90, - array( self::TEST_HEIGHT, self::TEST_WIDTH ) - ), - array( - 180, - array( self::TEST_WIDTH, self::TEST_HEIGHT ) - ), - array( - 270, - array( self::TEST_HEIGHT, self::TEST_WIDTH ) - ), - ); - } -} - diff --git a/tests/phpunit/includes/media/ExifTest.php b/tests/phpunit/includes/media/ExifTest.php deleted file mode 100644 index 045777d7..00000000 --- a/tests/phpunit/includes/media/ExifTest.php +++ /dev/null @@ -1,48 +0,0 @@ -mediaPath = __DIR__ . '/../../data/media/'; - - if ( !wfDl( 'exif' ) ) { - $this->markTestSkipped( "This test needs the exif extension." ); - } - global $wgShowEXIF; - $this->showExif = $wgShowEXIF; - $wgShowEXIF = true; - } - - public function tearDown() { - global $wgShowEXIF; - $wgShowEXIF = $this->showExif; - } - - public function testGPSExtraction() { - $filename = $this->mediaPath . 'exif-gps.jpg'; - $seg = JpegMetadataExtractor::segmentSplitter( $filename ); - $exif = new Exif( $filename, $seg['byteOrder'] ); - $data = $exif->getFilteredData(); - $expected = array( - 'GPSLatitude' => 88.5180555556, - 'GPSLongitude' => -21.12357, - 'GPSAltitude' => -3.141592653, - 'GPSDOP' => '5/1', - 'GPSVersionID' => '2.2.0.0', - ); - $this->assertEquals( $expected, $data, '', 0.0000000001 ); - } - - public function testUnicodeUserComment() { - $filename = $this->mediaPath . 'exif-user-comment.jpg'; - $seg = JpegMetadataExtractor::segmentSplitter( $filename ); - $exif = new Exif( $filename, $seg['byteOrder'] ); - $data = $exif->getFilteredData(); - - $expected = array( - 'UserComment' => 'test⁔comment' - ); - $this->assertEquals( $expected, $data ); - } - - -} diff --git a/tests/phpunit/includes/media/FormatMetadataTest.php b/tests/phpunit/includes/media/FormatMetadataTest.php deleted file mode 100644 index 6ade6702..00000000 --- a/tests/phpunit/includes/media/FormatMetadataTest.php +++ /dev/null @@ -1,52 +0,0 @@ -markTestSkipped( "This test needs the exif extension." ); - } - $filePath = __DIR__ . '/../../data/media'; - $this->backend = new FSFileBackend( array( - 'name' => 'localtesting', - 'lockManager' => 'nullLockManager', - 'containerPaths' => array( 'data' => $filePath ) - ) ); - $this->repo = new FSRepo( array( - 'name' => 'temp', - 'url' => 'http://localhost/thumbtest', - 'backend' => $this->backend - ) ); - global $wgShowEXIF; - $this->show = $wgShowEXIF; - $wgShowEXIF = true; - } - public function tearDown() { - global $wgShowEXIF; - $wgShowEXIF = $this->show; - } - - public function testInvalidDate() { - $file = $this->dataFile( 'broken_exif_date.jpg', 'image/jpeg' ); - - // Throws an error if bug hit - $meta = $file->formatMetadata(); - $this->assertNotEquals( false, $meta, 'Valid metadata extracted' ); - - // Find date exif entry - $this->assertArrayHasKey( 'visible', $meta ); - $dateIndex = null; - foreach ( $meta['visible'] as $i => $data ) { - if ( $data['id'] == 'exif-datetimeoriginal' ) { - $dateIndex = $i; - } - } - $this->assertNotNull( $dateIndex, 'Date entry exists in metadata' ); - $this->assertEquals( '0000:01:00 00:02:27', - $meta['visible'][$dateIndex]['value'], - 'File with invalid date metadata (bug 29471)' ); - } - - private function dataFile( $name, $type ) { - return new UnregisteredLocalFile( false, $this->repo, - "mwstore://localtesting/data/$name", $type ); - } -} diff --git a/tests/phpunit/includes/media/GIFMetadataExtractorTest.php b/tests/phpunit/includes/media/GIFMetadataExtractorTest.php deleted file mode 100644 index 650fdd5c..00000000 --- a/tests/phpunit/includes/media/GIFMetadataExtractorTest.php +++ /dev/null @@ -1,96 +0,0 @@ -mediaPath = __DIR__ . '/../../data/media/'; - } - /** - * Put in a file, and see if the metadata coming out is as expected. - * @param $filename String - * @param $expected Array The extracted metadata. - * @dataProvider dataGetMetadata - */ - public function testGetMetadata( $filename, $expected ) { - $actual = GIFMetadataExtractor::getMetadata( $this->mediaPath . $filename ); - $this->assertEquals( $expected, $actual ); - } - public function dataGetMetadata() { - - $xmpNugget = << - - - - - The interwebs - - - - Bawolff - - - A file to test GIF - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -EOF; - $xmpNugget = str_replace( "\r", '', $xmpNugget ); // Windows compat - - return array( - array( 'nonanimated.gif', array( - 'comment' => array( 'GIF test file ⁕ Created with GIMP' ), - 'duration' => 0.1, - 'frameCount' => 1, - 'looped' => false, - 'xmp' => '', - ) - ), - array( 'animated.gif', array( - 'comment' => array( 'GIF test file . Created with GIMP' ), - 'duration' => 2.4, - 'frameCount' => 4, - 'looped' => true, - 'xmp' => '', - ) - ), - - array( 'animated-xmp.gif', array( - 'xmp' => $xmpNugget, - 'duration' => 2.4, - 'frameCount' => 4, - 'looped' => true, - 'comment' => array( 'GIƒ·test·file' ), - ) - ), - ); - } -} diff --git a/tests/phpunit/includes/media/GIFTest.php b/tests/phpunit/includes/media/GIFTest.php deleted file mode 100644 index 5dcbeee0..00000000 --- a/tests/phpunit/includes/media/GIFTest.php +++ /dev/null @@ -1,98 +0,0 @@ -filePath = __DIR__ . '/../../data/media'; - $this->backend = new FSFileBackend( array( - 'name' => 'localtesting', - 'lockManager' => 'nullLockManager', - 'containerPaths' => array( 'data' => $this->filePath ) - ) ); - $this->repo = new FSRepo( array( - 'name' => 'temp', - 'url' => 'http://localhost/thumbtest', - 'backend' => $this->backend - ) ); - $this->handler = new GIFHandler(); - } - - public function testInvalidFile() { - $res = $this->handler->getMetadata( null, $this->filePath . '/README' ); - $this->assertEquals( GIFHandler::BROKEN_FILE, $res ); - } - /** - * @param $filename String basename of the file to check - * @param $expected boolean Expected result. - * @dataProvider dataIsAnimated - */ - public function testIsAnimanted( $filename, $expected ) { - $file = $this->dataFile( $filename, 'image/gif' ); - $actual = $this->handler->isAnimatedImage( $file ); - $this->assertEquals( $expected, $actual ); - } - public function dataIsAnimated() { - return array( - array( 'animated.gif', true ), - array( 'nonanimated.gif', false ), - ); - } - - /** - * @param $filename String - * @param $expected Integer Total image area - * @dataProvider dataGetImageArea - */ - public function testGetImageArea( $filename, $expected ) { - $file = $this->dataFile( $filename, 'image/gif' ); - $actual = $this->handler->getImageArea( $file, $file->getWidth(), $file->getHeight() ); - $this->assertEquals( $expected, $actual ); - } - public function dataGetImageArea() { - return array( - array( 'animated.gif', 5400 ), - array( 'nonanimated.gif', 1350 ), - ); - } - - /** - * @param $metadata String Serialized metadata - * @param $expected Integer One of the class constants of GIFHandler - * @dataProvider dataIsMetadataValid - */ - public function testIsMetadataValid( $metadata, $expected ) { - $actual = $this->handler->isMetadataValid( null, $metadata ); - $this->assertEquals( $expected, $actual ); - } - public function dataIsMetadataValid() { - return array( - array( GIFHandler::BROKEN_FILE, GIFHandler::METADATA_GOOD ), - array( '', GIFHandler::METADATA_BAD ), - array( null, GIFHandler::METADATA_BAD ), - array( 'Something invalid!', GIFHandler::METADATA_BAD ), - array( 'a:4:{s:10:"frameCount";i:1;s:6:"looped";b:0;s:8:"duration";d:0.1000000000000000055511151231257827021181583404541015625;s:8:"metadata";a:2:{s:14:"GIFFileComment";a:1:{i:0;s:35:"GIF test file ⁕ Created with GIMP";}s:15:"_MW_GIF_VERSION";i:1;}}', GIFHandler::METADATA_GOOD ), - ); - } - - /** - * @param $filename String - * @param $expected String Serialized array - * @dataProvider dataGetMetadata - */ - public function testGetMetadata( $filename, $expected ) { - $file = $this->dataFile( $filename, 'image/gif' ); - $actual = $this->handler->getMetadata( $file, "$this->filePath/$filename" ); - $this->assertEquals( unserialize( $expected ), unserialize( $actual ) ); - } - - public function dataGetMetadata() { - return array( - array( 'nonanimated.gif', 'a:4:{s:10:"frameCount";i:1;s:6:"looped";b:0;s:8:"duration";d:0.1000000000000000055511151231257827021181583404541015625;s:8:"metadata";a:2:{s:14:"GIFFileComment";a:1:{i:0;s:35:"GIF test file ⁕ Created with GIMP";}s:15:"_MW_GIF_VERSION";i:1;}}' ), - array( 'animated-xmp.gif', 'a:4:{s:10:"frameCount";i:4;s:6:"looped";b:1;s:8:"duration";d:2.399999999999999911182158029987476766109466552734375;s:8:"metadata";a:5:{s:6:"Artist";s:7:"Bawolff";s:16:"ImageDescription";a:2:{s:9:"x-default";s:18:"A file to test GIF";s:5:"_type";s:4:"lang";}s:15:"SublocationDest";s:13:"The interwebs";s:14:"GIFFileComment";a:1:{i:0;s:16:"GIƒ·test·file";}s:15:"_MW_GIF_VERSION";i:1;}}' ), - ); - } - - private function dataFile( $name, $type ) { - return new UnregisteredLocalFile( false, $this->repo, - "mwstore://localtesting/data/$name", $type ); - } -} diff --git a/tests/phpunit/includes/media/IPTCTest.php b/tests/phpunit/includes/media/IPTCTest.php deleted file mode 100644 index ec6deeb8..00000000 --- a/tests/phpunit/includes/media/IPTCTest.php +++ /dev/null @@ -1,55 +0,0 @@ -assertEquals( 'UTF-8', $res ); - } - - public function testIPTCParseNoCharset88591() { - // basically IPTC for keyword with value of 0xBC which is 1/4 in iso-8859-1 - // This data doesn't specify a charset. We're supposed to guess - // (which basically means utf-8 if valid, windows 1252 (iso 8859-1) if not) - $iptcData = "Photoshop 3.0\08BIM\4\4\0\0\0\0\0\x06\x1c\x02\x19\x00\x01\xBC"; - $res = IPTC::Parse( $iptcData ); - $this->assertEquals( array( '¼' ), $res['Keywords'] ); - } - /* This one contains a sequence that's valid iso 8859-1 but not valid utf8 */ - /* \xC3 = Ã, \xB8 = ¸ */ - public function testIPTCParseNoCharset88591b() { - $iptcData = "Photoshop 3.0\08BIM\4\4\0\0\0\0\0\x09\x1c\x02\x19\x00\x04\xC3\xC3\xC3\xB8"; - $res = IPTC::Parse( $iptcData ); - $this->assertEquals( array( 'ÃÃø' ), $res['Keywords'] ); - } - /* Same as testIPTCParseNoCharset88591b, but forcing the charset to utf-8. - * What should happen is the first "\xC3\xC3" should be dropped as invalid, - * leaving \xC3\xB8, which is ø - */ - public function testIPTCParseForcedUTFButInvalid() { - $iptcData = "Photoshop 3.0\08BIM\4\4\0\0\0\0\0\x11\x1c\x02\x19\x00\x04\xC3\xC3\xC3\xB8" - . "\x1c\x01\x5A\x00\x03\x1B\x25\x47"; - $res = IPTC::Parse( $iptcData ); - $this->assertEquals( array( 'ø' ), $res['Keywords'] ); - } - public function testIPTCParseNoCharsetUTF8() { - $iptcData = "Photoshop 3.0\08BIM\4\4\0\0\0\0\0\x07\x1c\x02\x19\x00\x02¼"; - $res = IPTC::Parse( $iptcData ); - $this->assertEquals( array( '¼' ), $res['Keywords'] ); - } - // Testing something that has 2 values for keyword - public function testIPTCParseMulti() { - $iptcData = /* identifier */ "Photoshop 3.0\08BIM\4\4" - /* length */ . "\0\0\0\0\0\x0D" - . "\x1c\x02\x19" . "\x00\x01" . "\xBC" - . "\x1c\x02\x19" . "\x00\x02" . "\xBC\xBD"; - $res = IPTC::Parse( $iptcData ); - $this->assertEquals( array( '¼', '¼½' ), $res['Keywords'] ); - } - public function testIPTCParseUTF8() { - // This has the magic "\x1c\x01\x5A\x00\x03\x1B\x25\x47" which marks content as UTF8. - $iptcData = "Photoshop 3.0\08BIM\4\4\0\0\0\0\0\x0F\x1c\x02\x19\x00\x02¼\x1c\x01\x5A\x00\x03\x1B\x25\x47"; - $res = IPTC::Parse( $iptcData ); - $this->assertEquals( array( '¼' ), $res['Keywords'] ); - } - -} diff --git a/tests/phpunit/includes/media/JpegMetadataExtractorTest.php b/tests/phpunit/includes/media/JpegMetadataExtractorTest.php deleted file mode 100644 index 41d81190..00000000 --- a/tests/phpunit/includes/media/JpegMetadataExtractorTest.php +++ /dev/null @@ -1,94 +0,0 @@ -filePath = __DIR__ . '/../../data/media/'; - } - - /** - * We also use this test to test padding bytes don't - * screw stuff up - * - * @param $file filename - * - * @dataProvider dataUtf8Comment - */ - public function testUtf8Comment( $file ) { - $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . $file ); - $this->assertEquals( array( 'UTF-8 JPEG Comment — ¼' ), $res['COM'] ); - } - public function dataUtf8Comment() { - return array( - array( 'jpeg-comment-utf.jpg' ), - array( 'jpeg-padding-even.jpg' ), - array( 'jpeg-padding-odd.jpg' ), - ); - } - /** The file is iso-8859-1, but it should get auto converted */ - public function testIso88591Comment() { - $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-comment-iso8859-1.jpg' ); - $this->assertEquals( array( 'ISO-8859-1 JPEG Comment - ¼' ), $res['COM'] ); - } - /** Comment values that are non-textual (random binary junk) should not be shown. - * The example test file has a comment with a 0x5 byte in it which is a control character - * and considered binary junk for our purposes. - */ - public function testBinaryCommentStripped() { - $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-comment-binary.jpg' ); - $this->assertEmpty( $res['COM'] ); - } - /* Very rarely a file can have multiple comments. - * Order of comments is based on order inside the file. - */ - public function testMultipleComment() { - $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-comment-multiple.jpg' ); - $this->assertEquals( array( 'foo', 'bar' ), $res['COM'] ); - } - public function testXMPExtraction() { - $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-xmp-psir.jpg' ); - $expected = file_get_contents( $this->filePath . 'jpeg-xmp-psir.xmp' ); - $this->assertEquals( $expected, $res['XMP'] ); - } - public function testPSIRExtraction() { - $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-xmp-psir.jpg' ); - $expected = '50686f746f73686f7020332e30003842494d04040000000000181c02190004746573741c02190003666f6f1c020000020004'; - $this->assertEquals( $expected, bin2hex( $res['PSIR'][0] ) ); - } - public function testXMPExtractionAltAppId() { - $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-xmp-alt.jpg' ); - $expected = file_get_contents( $this->filePath . 'jpeg-xmp-psir.xmp' ); - $this->assertEquals( $expected, $res['XMP'] ); - } - - - public function testIPTCHashComparisionNoHash() { - $segments = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-xmp-psir.jpg' ); - $res = JpegMetadataExtractor::doPSIR( $segments['PSIR'][0] ); - - $this->assertEquals( 'iptc-no-hash', $res ); - } - public function testIPTCHashComparisionBadHash() { - $segments = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-iptc-bad-hash.jpg' ); - $res = JpegMetadataExtractor::doPSIR( $segments['PSIR'][0] ); - - $this->assertEquals( 'iptc-bad-hash', $res ); - } - public function testIPTCHashComparisionGoodHash() { - $segments = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'jpeg-iptc-good-hash.jpg' ); - $res = JpegMetadataExtractor::doPSIR( $segments['PSIR'][0] ); - - $this->assertEquals( 'iptc-good-hash', $res ); - } - public function testExifByteOrder() { - $res = JpegMetadataExtractor::segmentSplitter( $this->filePath . 'exif-user-comment.jpg' ); - $expected = 'BE'; - $this->assertEquals( $expected, $res['byteOrder'] ); - } -} diff --git a/tests/phpunit/includes/media/JpegTest.php b/tests/phpunit/includes/media/JpegTest.php deleted file mode 100644 index ea007f90..00000000 --- a/tests/phpunit/includes/media/JpegTest.php +++ /dev/null @@ -1,31 +0,0 @@ -filePath = __DIR__ . '/../../data/media/'; - if ( !wfDl( 'exif' ) ) { - $this->markTestSkipped( "This test needs the exif extension." ); - } - global $wgShowEXIF; - $this->show = $wgShowEXIF; - $wgShowEXIF = true; - } - public function tearDown() { - global $wgShowEXIF; - $wgShowEXIF = $this->show; - } - - public function testInvalidFile() { - $jpeg = new JpegHandler; - $res = $jpeg->getMetadata( null, $this->filePath . 'README' ); - $this->assertEquals( ExifBitmapHandler::BROKEN_FILE, $res ); - } - public function testJpegMetadataExtraction() { - $h = new JpegHandler; - $res = $h->getMetadata( null, $this->filePath . 'test.jpg' ); - $expected = 'a:7:{s:16:"ImageDescription";s:9:"Test file";s:11:"XResolution";s:4:"72/1";s:11:"YResolution";s:4:"72/1";s:14:"ResolutionUnit";i:2;s:16:"YCbCrPositioning";i:1;s:15:"JPEGFileComment";a:1:{i:0;s:17:"Created with GIMP";}s:22:"MEDIAWIKI_EXIF_VERSION";i:2;}'; - - // Unserialize in case serialization format ever changes. - $this->assertEquals( unserialize( $expected ), unserialize( $res ) ); - } -} diff --git a/tests/phpunit/includes/media/MediaHandlerTest.php b/tests/phpunit/includes/media/MediaHandlerTest.php deleted file mode 100644 index 99df4f80..00000000 --- a/tests/phpunit/includes/media/MediaHandlerTest.php +++ /dev/null @@ -1,50 +0,0 @@ - 50, - 'height' => 50, - 'tests' => array( - 50 => 50, - 17 => 17, - 18 => 18 ) ), - array( - 'width' => 366, - 'height' => 300, - 'tests' => array( - 50 => 61, - 17 => 21, - 18 => 22 ) ), - array( - 'width' => 300, - 'height' => 366, - 'tests' => array( - 50 => 41, - 17 => 14, - 18 => 15 ) ), - array( - 'width' => 100, - 'height' => 400, - 'tests' => array( - 50 => 12, - 17 => 4, - 18 => 4 ) ) ); - foreach ( $vals as $row ) { - $tests = $row['tests']; - $height = $row['height']; - $width = $row['width']; - foreach ( $tests as $max => $expected ) { - $y = round( $expected * $height / $width ); - $result = MediaHandler::fitBoxWidth( $width, $height, $max ); - $y2 = round( $result * $height / $width ); - $this->assertEquals( $expected, - $result, - "($width, $height, $max) wanted: {$expected}x$y, got: {$result}x$y2" ); - } - } - } -} - - diff --git a/tests/phpunit/includes/media/PNGMetadataExtractorTest.php b/tests/phpunit/includes/media/PNGMetadataExtractorTest.php deleted file mode 100644 index 1b1b2ec3..00000000 --- a/tests/phpunit/includes/media/PNGMetadataExtractorTest.php +++ /dev/null @@ -1,141 +0,0 @@ -filePath = __DIR__ . '/../../data/media/'; - } - /** - * Tests zTXt tag (compressed textual metadata) - */ - function testPngNativetZtxt() { - $meta = PNGMetadataExtractor::getMetadata( $this->filePath . - 'Png-native-test.png' ); - $expected = "foo bar baz foo foo foo foof foo foo foo foo"; - $this->assertArrayHasKey( 'text', $meta ); - $meta = $meta['text']; - $this->assertArrayHasKey( 'Make', $meta ); - $this->assertArrayHasKey( 'x-default', $meta['Make'] ); - - $this->assertEquals( $expected, $meta['Make']['x-default'] ); - } - - /** - * Test tEXt tag (Uncompressed textual metadata) - */ - function testPngNativeText() { - $meta = PNGMetadataExtractor::getMetadata( $this->filePath . - 'Png-native-test.png' ); - $expected = "Some long image desc"; - $this->assertArrayHasKey( 'text', $meta ); - $meta = $meta['text']; - $this->assertArrayHasKey( 'ImageDescription', $meta ); - $this->assertArrayHasKey( 'x-default', $meta['ImageDescription'] ); - $this->assertArrayHasKey( '_type', $meta['ImageDescription'] ); - - $this->assertEquals( $expected, $meta['ImageDescription']['x-default'] ); - } - - /** - * tEXt tags must be encoded iso-8859-1 (vs iTXt which are utf-8) - * Make sure non-ascii characters get converted properly - */ - function testPngNativeTextNonAscii() { - $meta = PNGMetadataExtractor::getMetadata( $this->filePath . - 'Png-native-test.png' ); - - // Note the Copyright symbol here is a utf-8 one - // (aka \xC2\xA9) where in the file its iso-8859-1 - // encoded as just \xA9. - $expected = "© 2010 Bawolff"; - - - $this->assertArrayHasKey( 'text', $meta ); - $meta = $meta['text']; - $this->assertArrayHasKey( 'Copyright', $meta ); - $this->assertArrayHasKey( 'x-default', $meta['Copyright'] ); - - $this->assertEquals( $expected, $meta['Copyright']['x-default'] ); - } - - /** - * Test extraction of pHYs tags, which can tell what the - * actual resolution of the image is (aka in dots per meter). - function testPngPhysTag () { - $meta = PNGMetadataExtractor::getMetadata( $this->filePath . - 'Png-native-test.png' ); - - $this->assertArrayHasKey( 'text', $meta ); - $meta = $meta['text']; - - $this->assertEquals( '2835/100', $meta['XResolution'] ); - $this->assertEquals( '2835/100', $meta['YResolution'] ); - $this->assertEquals( 3, $meta['ResolutionUnit'] ); // 3 = cm - } - - /** - * Given a normal static PNG, check the animation metadata returned. - */ - function testStaticPngAnimationMetadata() { - $meta = PNGMetadataExtractor::getMetadata( $this->filePath . - 'Png-native-test.png' ); - - $this->assertEquals( 0, $meta['frameCount'] ); - $this->assertEquals( 1, $meta['loopCount'] ); - $this->assertEquals( 0, $meta['duration'] ); - } - - /** - * Given an animated APNG image file - * check it gets animated metadata right. - */ - function testApngAnimationMetadata() { - $meta = PNGMetadataExtractor::getMetadata( $this->filePath . - 'Animated_PNG_example_bouncing_beach_ball.png' ); - - $this->assertEquals( 20, $meta['frameCount'] ); - // Note loop count of 0 = infinity - $this->assertEquals( 0, $meta['loopCount'] ); - $this->assertEquals( 1.5, $meta['duration'], '', 0.00001 ); - } - - function testPngBitDepth8() { - $meta = PNGMetadataExtractor::getMetadata( $this->filePath . - 'Png-native-test.png' ); - - $this->assertEquals( 8, $meta['bitDepth'] ); - } - function testPngBitDepth1() { - $meta = PNGMetadataExtractor::getMetadata( $this->filePath . - '1bit-png.png' ); - $this->assertEquals( 1, $meta['bitDepth'] ); - } - - - function testPngIndexColour() { - $meta = PNGMetadataExtractor::getMetadata( $this->filePath . - 'Png-native-test.png' ); - - $this->assertEquals( 'index-coloured', $meta['colorType'] ); - } - function testPngRgbColour() { - $meta = PNGMetadataExtractor::getMetadata( $this->filePath . - 'rgb-png.png' ); - $this->assertEquals( 'truecolour-alpha', $meta['colorType'] ); - } - function testPngRgbNoAlphaColour() { - $meta = PNGMetadataExtractor::getMetadata( $this->filePath . - 'rgb-na-png.png' ); - $this->assertEquals( 'truecolour', $meta['colorType'] ); - } - function testPngGreyscaleColour() { - $meta = PNGMetadataExtractor::getMetadata( $this->filePath . - 'greyscale-png.png' ); - $this->assertEquals( 'greyscale-alpha', $meta['colorType'] ); - } - function testPngGreyscaleNoAlphaColour() { - $meta = PNGMetadataExtractor::getMetadata( $this->filePath . - 'greyscale-na-png.png' ); - $this->assertEquals( 'greyscale', $meta['colorType'] ); - } - -} diff --git a/tests/phpunit/includes/media/PNGTest.php b/tests/phpunit/includes/media/PNGTest.php deleted file mode 100644 index fe73c9c7..00000000 --- a/tests/phpunit/includes/media/PNGTest.php +++ /dev/null @@ -1,100 +0,0 @@ -filePath = __DIR__ . '/../../data/media'; - $this->backend = new FSFileBackend( array( - 'name' => 'localtesting', - 'lockManager' => 'nullLockManager', - 'containerPaths' => array( 'data' => $this->filePath ) - ) ); - $this->repo = new FSRepo( array( - 'name' => 'temp', - 'url' => 'http://localhost/thumbtest', - 'backend' => $this->backend - ) ); - $this->handler = new PNGHandler(); - } - - public function testInvalidFile() { - $res = $this->handler->getMetadata( null, $this->filePath . '/README' ); - $this->assertEquals( PNGHandler::BROKEN_FILE, $res ); - } - /** - * @param $filename String basename of the file to check - * @param $expected boolean Expected result. - * @dataProvider dataIsAnimated - */ - public function testIsAnimanted( $filename, $expected ) { - $file = $this->dataFile( $filename, 'image/png' ); - $actual = $this->handler->isAnimatedImage( $file ); - $this->assertEquals( $expected, $actual ); - } - public function dataIsAnimated() { - return array( - array( 'Animated_PNG_example_bouncing_beach_ball.png', true ), - array( '1bit-png.png', false ), - ); - } - - /** - * @param $filename String - * @param $expected Integer Total image area - * @dataProvider dataGetImageArea - */ - public function testGetImageArea( $filename, $expected ) { - $file = $this->dataFile($filename, 'image/png' ); - $actual = $this->handler->getImageArea( $file, $file->getWidth(), $file->getHeight() ); - $this->assertEquals( $expected, $actual ); - } - public function dataGetImageArea() { - return array( - array( '1bit-png.png', 2500 ), - array( 'greyscale-png.png', 2500 ), - array( 'Png-native-test.png', 126000 ), - array( 'Animated_PNG_example_bouncing_beach_ball.png', 10000 ), - ); - } - - /** - * @param $metadata String Serialized metadata - * @param $expected Integer One of the class constants of PNGHandler - * @dataProvider dataIsMetadataValid - */ - public function testIsMetadataValid( $metadata, $expected ) { - $actual = $this->handler->isMetadataValid( null, $metadata ); - $this->assertEquals( $expected, $actual ); - } - public function dataIsMetadataValid() { - return array( - array( PNGHandler::BROKEN_FILE, PNGHandler::METADATA_GOOD ), - array( '', PNGHandler::METADATA_BAD ), - array( null, PNGHandler::METADATA_BAD ), - array( 'Something invalid!', PNGHandler::METADATA_BAD ), - array( 'a:6:{s:10:"frameCount";i:0;s:9:"loopCount";i:1;s:8:"duration";d:0;s:8:"bitDepth";i:8;s:9:"colorType";s:10:"truecolour";s:8:"metadata";a:1:{s:15:"_MW_PNG_VERSION";i:1;}}', PNGHandler::METADATA_GOOD ), - ); - } - - /** - * @param $filename String - * @param $expected String Serialized array - * @dataProvider dataGetMetadata - */ - public function testGetMetadata( $filename, $expected ) { - $file = $this->dataFile( $filename, 'image/png' ); - $actual = $this->handler->getMetadata( $file, "$this->filePath/$filename" ); -// $this->assertEquals( unserialize( $expected ), unserialize( $actual ) ); - $this->assertEquals( ( $expected ), ( $actual ) ); - } - public function dataGetMetadata() { - return array( - array( 'rgb-na-png.png', 'a:6:{s:10:"frameCount";i:0;s:9:"loopCount";i:1;s:8:"duration";d:0;s:8:"bitDepth";i:8;s:9:"colorType";s:10:"truecolour";s:8:"metadata";a:1:{s:15:"_MW_PNG_VERSION";i:1;}}' ), - array( 'xmp.png', 'a:6:{s:10:"frameCount";i:0;s:9:"loopCount";i:1;s:8:"duration";d:0;s:8:"bitDepth";i:1;s:9:"colorType";s:14:"index-coloured";s:8:"metadata";a:2:{s:12:"SerialNumber";s:9:"123456789";s:15:"_MW_PNG_VERSION";i:1;}}' ), - ); - } - - private function dataFile( $name, $type ) { - return new UnregisteredLocalFile( false, $this->repo, - "mwstore://localtesting/data/$name", $type ); - } -} diff --git a/tests/phpunit/includes/media/SVGMetadataExtractorTest.php b/tests/phpunit/includes/media/SVGMetadataExtractorTest.php deleted file mode 100644 index 2116554e..00000000 --- a/tests/phpunit/includes/media/SVGMetadataExtractorTest.php +++ /dev/null @@ -1,108 +0,0 @@ -assertMetadata( $infile, $expected ); - } - - /** - * @dataProvider providerSvgFilesWithXMLMetadata - */ - function testGetXMLMetadata( $infile, $expected ) { - $r = new XMLReader(); - if( !method_exists( $r, 'readInnerXML' ) ) { - $this->markTestSkipped( 'XMLReader::readInnerXML() does not exist (libxml >2.6.20 needed).' ); - return; - } - $this->assertMetadata( $infile, $expected ); - } - - function assertMetadata( $infile, $expected ) { - try { - $data = SVGMetadataExtractor::getMetadata( $infile ); - $this->assertEquals( $expected, $data, 'SVG metadata extraction test' ); - } catch ( MWException $e ) { - if ( $expected === false ) { - $this->assertTrue( true, 'SVG metadata extracted test (expected failure)' ); - } else { - throw $e; - } - } - } - - function providerSvgFiles() { - $base = __DIR__ . '/../../data/media'; - return array( - array( - "$base/Wikimedia-logo.svg", - array( - 'width' => 1024, - 'height' => 1024, - 'originalWidth' => '1024', - 'originalHeight' => '1024', - ) - ), - array( - "$base/QA_icon.svg", - array( - 'width' => 60, - 'height' => 60, - 'originalWidth' => '60', - 'originalHeight' => '60', - ) - ), - array( - "$base/Gtk-media-play-ltr.svg", - array( - 'width' => 60, - 'height' => 60, - 'originalWidth' => '60.0000000', - 'originalHeight' => '60.0000000', - ) - ), - array( - "$base/Toll_Texas_1.svg", - // This file triggered bug 31719, needs entity expansion in the xmlns checks - array( - 'width' => 385, - 'height' => 385, - 'originalWidth' => '385', - 'originalHeight' => '385.0004883', - ) - ) - ); - } - - function providerSvgFilesWithXMLMetadata() { - $base = __DIR__ . '/../../data/media'; - $metadata = - ' - - image/svg+xml - - - '; - $metadata = str_replace( "\r", '', $metadata ); // Windows compat - return array( - array( - "$base/US_states_by_total_state_tax_revenue.svg", - array( - 'height' => 593, - 'metadata' => $metadata, - 'width' => 959, - 'originalWidth' => '958.69', - 'originalHeight' => '592.78998', - ) - ), - ); - } -} - diff --git a/tests/phpunit/includes/media/TiffTest.php b/tests/phpunit/includes/media/TiffTest.php deleted file mode 100644 index 4c79f66c..00000000 --- a/tests/phpunit/includes/media/TiffTest.php +++ /dev/null @@ -1,35 +0,0 @@ -showExif = $wgShowEXIF; - $wgShowEXIF = true; - $this->filePath = __DIR__ . '/../../data/media/'; - $this->handler = new TiffHandler; - } - - public function tearDown() { - global $wgShowEXIF; - $wgShowEXIF = $this->showExif; - } - - public function testInvalidFile() { - if ( !wfDl( 'exif' ) ) { - $this->markTestIncomplete( "This test needs the exif extension." ); - } - $res = $this->handler->getMetadata( null, $this->filePath . 'README' ); - $this->assertEquals( ExifBitmapHandler::BROKEN_FILE, $res ); - } - - public function testTiffMetadataExtraction() { - if ( !wfDl( 'exif' ) ) { - $this->markTestIncomplete( "This test needs the exif extension." ); - } - $res = $this->handler->getMetadata( null, $this->filePath . 'test.tiff' ); - $expected = 'a:16:{s:10:"ImageWidth";i:20;s:11:"ImageLength";i:20;s:13:"BitsPerSample";a:3:{i:0;i:8;i:1;i:8;i:2;i:8;}s:11:"Compression";i:5;s:25:"PhotometricInterpretation";i:2;s:16:"ImageDescription";s:17:"Created with GIMP";s:12:"StripOffsets";i:8;s:11:"Orientation";i:1;s:15:"SamplesPerPixel";i:3;s:12:"RowsPerStrip";i:64;s:15:"StripByteCounts";i:238;s:11:"XResolution";s:19:"1207959552/16777216";s:11:"YResolution";s:19:"1207959552/16777216";s:19:"PlanarConfiguration";i:1;s:14:"ResolutionUnit";i:2;s:22:"MEDIAWIKI_EXIF_VERSION";i:2;}'; - // Re-unserialize in case there are subtle differences between how versions - // of php serialize stuff. - $this->assertEquals( unserialize( $expected ), unserialize( $res ) ); - } -} diff --git a/tests/phpunit/includes/media/XMPTest.php b/tests/phpunit/includes/media/XMPTest.php deleted file mode 100644 index 8198d3b0..00000000 --- a/tests/phpunit/includes/media/XMPTest.php +++ /dev/null @@ -1,158 +0,0 @@ -markTestSkipped( 'Requires libxml to do XMP parsing' ); - } - } - - /** - * Put XMP in, compare what comes out... - * - * @param $xmp String the actual xml data. - * @param $expected Array expected result of parsing the xmp. - * @param $info String Short sentence on what's being tested. - * - * @dataProvider dataXMPParse - */ - public function testXMPParse( $xmp, $expected, $info ) { - if ( !is_string( $xmp ) || !is_array( $expected ) ) { - throw new Exception( "Invalid data provided to " . __METHOD__ ); - } - $reader = new XMPReader; - $reader->parse( $xmp ); - $this->assertEquals( $expected, $reader->getResults(), $info, 0.0000000001 ); - } - - public function dataXMPParse() { - $xmpPath = __DIR__ . '/../../data/xmp/' ; - $data = array(); - - // $xmpFiles format: array of arrays with first arg file base name, - // with the actual file having .xmp on the end for the xmp - // and .result.php on the end for a php file containing the result - // array. Second argument is some info on what's being tested. - $xmpFiles = array( - array( '1', 'parseType=Resource test' ), - array( '2', 'Structure with mixed attribute and element props' ), - array( '3', 'Extra qualifiers (that should be ignored)' ), - array( '3-invalid', 'Test ignoring qualifiers that look like normal props' ), - array( '4', 'Flash as qualifier' ), - array( '5', 'Flash as qualifier 2' ), - array( '6', 'Multiple rdf:Description' ), - array( '7', 'Generic test of several property types' ), - array( 'flash', 'Test of Flash property' ), - array( 'invalid-child-not-struct', 'Test child props not in struct or ignored' ), - array( 'no-recognized-props', 'Test namespace and no recognized props' ), - array( 'no-namespace', 'Test non-namespaced attributes are ignored' ), - array( 'bag-for-seq', "Allow bag's instead of seq's. (bug 27105)" ), - array( 'utf16BE', 'UTF-16BE encoding' ), - array( 'utf16LE', 'UTF-16LE encoding' ), - array( 'utf32BE', 'UTF-32BE encoding' ), - array( 'utf32LE', 'UTF-32LE encoding' ), - array( 'xmpExt', 'Extended XMP missing second part' ), - array( 'gps', 'Handling of exif GPS parameters in XMP' ), - ); - foreach( $xmpFiles as $file ) { - $xmp = file_get_contents( $xmpPath . $file[0] . '.xmp' ); - // I'm not sure if this is the best way to handle getting the - // result array, but it seems kind of big to put directly in the test - // file. - $result = null; - include( $xmpPath . $file[0] . '.result.php' ); - $data[] = array( $xmp, $result, '[' . $file[0] . '.xmp] ' . $file[1] ); - } - return $data; - } - - /** Test ExtendedXMP block support. (Used when the XMP has to be split - * over multiple jpeg segments, due to 64k size limit on jpeg segments. - * - * @todo This is based on what the standard says. Need to find a real - * world example file to double check the support for this is right. - */ - function testExtendedXMP() { - $xmpPath = __DIR__ . '/../../data/xmp/'; - $standardXMP = file_get_contents( $xmpPath . 'xmpExt.xmp' ); - $extendedXMP = file_get_contents( $xmpPath . 'xmpExt2.xmp' ); - - $md5sum = '28C74E0AC2D796886759006FBE2E57B7'; // of xmpExt2.xmp - $length = pack( 'N', strlen( $extendedXMP ) ); - $offset = pack( 'N', 0 ); - $extendedPacket = $md5sum . $length . $offset . $extendedXMP; - - $reader = new XMPReader(); - $reader->parse( $standardXMP ); - $reader->parseExtended( $extendedPacket ); - $actual = $reader->getResults(); - - $expected = array( 'xmp-exif' => - array( - 'DigitalZoomRatio' => '0/10', - 'Flash' => 9, - 'FNumber' => '2/10', - ) - ); - - $this->assertEquals( $expected, $actual ); - } - - /** - * This test has an extended XMP block with a wrong guid (md5sum) - * and thus should only return the StandardXMP, not the ExtendedXMP. - */ - function testExtendedXMPWithWrongGUID() { - $xmpPath = __DIR__ . '/../../data/xmp/'; - $standardXMP = file_get_contents( $xmpPath . 'xmpExt.xmp' ); - $extendedXMP = file_get_contents( $xmpPath . 'xmpExt2.xmp' ); - - $md5sum = '28C74E0AC2D796886759006FBE2E57B9'; // Note last digit. - $length = pack( 'N', strlen( $extendedXMP ) ); - $offset = pack( 'N', 0 ); - $extendedPacket = $md5sum . $length . $offset . $extendedXMP; - - $reader = new XMPReader(); - $reader->parse( $standardXMP ); - $reader->parseExtended( $extendedPacket ); - $actual = $reader->getResults(); - - $expected = array( 'xmp-exif' => - array( - 'DigitalZoomRatio' => '0/10', - 'Flash' => 9, - ) - ); - - $this->assertEquals( $expected, $actual ); - } - /** - * Have a high offset to simulate a missing packet, - * which should cause it to ignore the ExtendedXMP packet. - */ - function testExtendedXMPMissingPacket() { - $xmpPath = __DIR__ . '/../../data/xmp/'; - $standardXMP = file_get_contents( $xmpPath . 'xmpExt.xmp' ); - $extendedXMP = file_get_contents( $xmpPath . 'xmpExt2.xmp' ); - - $md5sum = '28C74E0AC2D796886759006FBE2E57B7'; // of xmpExt2.xmp - $length = pack( 'N', strlen( $extendedXMP ) ); - $offset = pack( 'N', 2048 ); - $extendedPacket = $md5sum . $length . $offset . $extendedXMP; - - $reader = new XMPReader(); - $reader->parse( $standardXMP ); - $reader->parseExtended( $extendedPacket ); - $actual = $reader->getResults(); - - $expected = array( 'xmp-exif' => - array( - 'DigitalZoomRatio' => '0/10', - 'Flash' => 9, - ) - ); - - $this->assertEquals( $expected, $actual ); - } - -} diff --git a/tests/phpunit/includes/media/XMPValidateTest.php b/tests/phpunit/includes/media/XMPValidateTest.php deleted file mode 100644 index e2bb8d8d..00000000 --- a/tests/phpunit/includes/media/XMPValidateTest.php +++ /dev/null @@ -1,47 +0,0 @@ -assertEquals( $expected, $value ); - } - - function providerDate() { - /* For reference valid date formats are: - * YYYY - * YYYY-MM - * YYYY-MM-DD - * YYYY-MM-DDThh:mmTZD - * YYYY-MM-DDThh:mm:ssTZD - * YYYY-MM-DDThh:mm:ss.sTZD - * (Time zone is optional) - */ - return array( - array( '1992', '1992' ), - array( '1992-04', '1992:04' ), - array( '1992-02-01', '1992:02:01' ), - array( '2011-09-29', '2011:09:29' ), - array( '1982-12-15T20:12', '1982:12:15 20:12' ), - array( '1982-12-15T20:12Z', '1982:12:15 20:12' ), - array( '1982-12-15T20:12+02:30', '1982:12:15 22:42' ), - array( '1982-12-15T01:12-02:30', '1982:12:14 22:42' ), - array( '1982-12-15T20:12:11', '1982:12:15 20:12:11' ), - array( '1982-12-15T20:12:11Z', '1982:12:15 20:12:11' ), - array( '1982-12-15T20:12:11+01:10', '1982:12:15 21:22:11' ), - array( '2045-12-15T20:12:11', '2045:12:15 20:12:11' ), - array( '1867-06-01T15:00:00', '1867:06:01 15:00:00' ), - /* some invalid ones */ - array( '2001--12', null ), - array( '2001-5-12', null ), - array( '2001-5-12TZ', null ), - array( '2001-05-12T15', null ), - array( '2001-12T15:13', null ), - ); - - } - -} diff --git a/tests/phpunit/includes/mobile/DeviceDetectionTest.php b/tests/phpunit/includes/mobile/DeviceDetectionTest.php deleted file mode 100644 index 0e156532..00000000 --- a/tests/phpunit/includes/mobile/DeviceDetectionTest.php +++ /dev/null @@ -1,40 +0,0 @@ -assertEquals( $format, $detector->detectFormatName( $userAgent ) ); - } - - public function provideTestFormatName() { - return array( - array( 'android', 'Mozilla/5.0 (Linux; U; Android 2.1; en-us; Nexus One Build/ERD62) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17' ), - array( 'iphone2', 'Mozilla/5.0 (ipod: U;CPU iPhone OS 2_2 like Mac OS X: es_es) AppleWebKit/525.18.1 (KHTML, like Gecko) Version/3.0 Mobile/3B48b Safari/419.3' ), - array( 'iphone', 'Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3B48b Safari/419.3' ), - array( 'nokia', 'Mozilla/5.0 (SymbianOS/9.1; U; [en]; SymbianOS/91 Series60/3.0) AppleWebKit/413 (KHTML, like Gecko) Safari/413' ), - array( 'palm_pre', 'Mozilla/5.0 (webOS/1.0; U; en-US) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/1.0 Safari/525.27.1 Pre/1.0' ), - array( 'wii', 'Opera/9.00 (Nintendo Wii; U; ; 1309-9; en)' ), - array( 'operamini', 'Opera/9.50 (J2ME/MIDP; Opera Mini/4.0.10031/298; U; en)' ), - array( 'operamobile', 'Opera/9.51 Beta (Microsoft Windows; PPC; Opera Mobi/1718; U; en)' ), - array( 'kindle', 'Mozilla/4.0 (compatible; Linux 2.6.10) NetFront/3.3 Kindle/1.0 (screen 600x800)' ), - array( 'kindle2', 'Mozilla/4.0 (compatible; Linux 2.6.22) NetFront/3.4 Kindle/2.0 (screen 824x1200; rotate)' ), - array( 'capable', 'Mozilla/5.0 (X11; Linux i686; rv:2.0.1) Gecko/20100101 Firefox/4.0.1' ), - array( 'netfront', 'Mozilla/4.08 (Windows; Mobile Content Viewer/1.0) NetFront/3.2' ), - array( 'wap2', 'SonyEricssonK608i/R2L/SN356841000828910 Browser/SEMC-Browser/4.2 Profile/MIDP-2.0 Configuration/CLDC-1.1' ), - array( 'wap2', 'NokiaN73-2/3.0-630.0.2 Series60/3.0 Profile/MIDP-2.0 Configuration/CLDC-1.1' ), - array( 'psp', 'Mozilla/4.0 (PSP (PlayStation Portable); 2.00)' ), - array( 'ps3', 'Mozilla/5.0 (PLAYSTATION 3; 1.00)' ), - array( 'ie', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)' ), - array( 'ie', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)' ), - array( 'blackberry', 'BlackBerry9300/5.0.0.716 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/133' ), - array( 'blackberry-lt5', 'BlackBerry7250/4.0.0 Profile/MIDP-2.0 Configuration/CLDC-1.1' ), - ); - } -} diff --git a/tests/phpunit/includes/normal/CleanUpTest.php b/tests/phpunit/includes/normal/CleanUpTest.php deleted file mode 100644 index d5ad18d8..00000000 --- a/tests/phpunit/includes/normal/CleanUpTest.php +++ /dev/null @@ -1,382 +0,0 @@ - - * http://www.mediawiki.org/ - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along - * with this program; if not, write to the Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - * http://www.gnu.org/copyleft/gpl.html - * - * @file - */ - -/** - * Additional tests for UtfNormal::cleanUp() function, inclusion - * regression checks for known problems. - * Requires PHPUnit. - * - * @ingroup UtfNormal - */ -class CleanUpTest extends MediaWikiTestCase { - /** @todo document */ - function testAscii() { - $text = 'This is plain ASCII text.'; - $this->assertEquals( $text, UtfNormal::cleanUp( $text ) ); - } - - /** @todo document */ - function testNull() { - $text = "a \x00 null"; - $expect = "a \xef\xbf\xbd null"; - $this->assertEquals( - bin2hex( $expect ), - bin2hex( UtfNormal::cleanUp( $text ) ) ); - } - - /** @todo document */ - function testLatin() { - $text = "L'\xc3\xa9cole"; - $this->assertEquals( $text, UtfNormal::cleanUp( $text ) ); - } - - /** @todo document */ - function testLatinNormal() { - $text = "L'e\xcc\x81cole"; - $expect = "L'\xc3\xa9cole"; - $this->assertEquals( $expect, UtfNormal::cleanUp( $text ) ); - } - - /** - * This test is *very* expensive! - * @todo document - */ - function XtestAllChars() { - $rep = UTF8_REPLACEMENT; - for( $i = 0x0; $i < UNICODE_MAX; $i++ ) { - $char = codepointToUtf8( $i ); - $clean = UtfNormal::cleanUp( $char ); - $x = sprintf( "%04X", $i ); - if( $i % 0x1000 == 0 ) echo "U+$x\n"; - if( $i == 0x0009 || - $i == 0x000a || - $i == 0x000d || - ($i > 0x001f && $i < UNICODE_SURROGATE_FIRST) || - ($i > UNICODE_SURROGATE_LAST && $i < 0xfffe ) || - ($i > 0xffff && $i <= UNICODE_MAX ) ) { - if( isset( UtfNormal::$utfCanonicalComp[$char] ) || isset( UtfNormal::$utfCanonicalDecomp[$char] ) ) { - $comp = UtfNormal::NFC( $char ); - $this->assertEquals( - bin2hex( $comp ), - bin2hex( $clean ), - "U+$x should be decomposed" ); - } else { - $this->assertEquals( - bin2hex( $char ), - bin2hex( $clean ), - "U+$x should be intact" ); - } - } else { - $this->assertEquals( bin2hex( $rep ), bin2hex( $clean ), $x ); - } - } - } - - /** @todo document */ - function testAllBytes() { - $this->doTestBytes( '', '' ); - $this->doTestBytes( 'x', '' ); - $this->doTestBytes( '', 'x' ); - $this->doTestBytes( 'x', 'x' ); - } - - /** @todo document */ - function doTestBytes( $head, $tail ) { - for( $i = 0x0; $i < 256; $i++ ) { - $char = $head . chr( $i ) . $tail; - $clean = UtfNormal::cleanUp( $char ); - $x = sprintf( "%02X", $i ); - if( $i == 0x0009 || - $i == 0x000a || - $i == 0x000d || - ($i > 0x001f && $i < 0x80) ) { - $this->assertEquals( - bin2hex( $char ), - bin2hex( $clean ), - "ASCII byte $x should be intact" ); - if( $char != $clean ) return; - } else { - $norm = $head . UTF8_REPLACEMENT . $tail; - $this->assertEquals( - bin2hex( $norm ), - bin2hex( $clean ), - "Forbidden byte $x should be rejected" ); - if( $norm != $clean ) return; - } - } - } - - /** @todo document */ - function testDoubleBytes() { - $this->doTestDoubleBytes( '', '' ); - $this->doTestDoubleBytes( 'x', '' ); - $this->doTestDoubleBytes( '', 'x' ); - $this->doTestDoubleBytes( 'x', 'x' ); - } - - /** - * @todo document - */ - function doTestDoubleBytes( $head, $tail ) { - for( $first = 0xc0; $first < 0x100; $first+=2 ) { - for( $second = 0x80; $second < 0x100; $second+=2 ) { - $char = $head . chr( $first ) . chr( $second ) . $tail; - $clean = UtfNormal::cleanUp( $char ); - $x = sprintf( "%02X,%02X", $first, $second ); - if( $first > 0xc1 && - $first < 0xe0 && - $second < 0xc0 ) { - $norm = UtfNormal::NFC( $char ); - $this->assertEquals( - bin2hex( $norm ), - bin2hex( $clean ), - "Pair $x should be intact" ); - if( $norm != $clean ) return; - } elseif( $first > 0xfd || $second > 0xbf ) { - # fe and ff are not legal head bytes -- expect two replacement chars - $norm = $head . UTF8_REPLACEMENT . UTF8_REPLACEMENT . $tail; - $this->assertEquals( - bin2hex( $norm ), - bin2hex( $clean ), - "Forbidden pair $x should be rejected" ); - if( $norm != $clean ) return; - } else { - $norm = $head . UTF8_REPLACEMENT . $tail; - $this->assertEquals( - bin2hex( $norm ), - bin2hex( $clean ), - "Forbidden pair $x should be rejected" ); - if( $norm != $clean ) return; - } - } - } - } - - /** @todo document */ - function testTripleBytes() { - $this->doTestTripleBytes( '', '' ); - $this->doTestTripleBytes( 'x', '' ); - $this->doTestTripleBytes( '', 'x' ); - $this->doTestTripleBytes( 'x', 'x' ); - } - - /** @todo document */ - function doTestTripleBytes( $head, $tail ) { - for( $first = 0xc0; $first < 0x100; $first+=2 ) { - for( $second = 0x80; $second < 0x100; $second+=2 ) { - #for( $third = 0x80; $third < 0x100; $third++ ) { - for( $third = 0x80; $third < 0x81; $third++ ) { - $char = $head . chr( $first ) . chr( $second ) . chr( $third ) . $tail; - $clean = UtfNormal::cleanUp( $char ); - $x = sprintf( "%02X,%02X,%02X", $first, $second, $third ); - if( $first >= 0xe0 && - $first < 0xf0 && - $second < 0xc0 && - $third < 0xc0 ) { - if( $first == 0xe0 && $second < 0xa0 ) { - $this->assertEquals( - bin2hex( $head . UTF8_REPLACEMENT . $tail ), - bin2hex( $clean ), - "Overlong triplet $x should be rejected" ); - } elseif( $first == 0xed && - ( chr( $first ) . chr( $second ) . chr( $third )) >= UTF8_SURROGATE_FIRST ) { - $this->assertEquals( - bin2hex( $head . UTF8_REPLACEMENT . $tail ), - bin2hex( $clean ), - "Surrogate triplet $x should be rejected" ); - } else { - $this->assertEquals( - bin2hex( UtfNormal::NFC( $char ) ), - bin2hex( $clean ), - "Triplet $x should be intact" ); - } - } elseif( $first > 0xc1 && $first < 0xe0 && $second < 0xc0 ) { - $this->assertEquals( - bin2hex( UtfNormal::NFC( $head . chr( $first ) . chr( $second ) ) . UTF8_REPLACEMENT . $tail ), - bin2hex( $clean ), - "Valid 2-byte $x + broken tail" ); - } elseif( $second > 0xc1 && $second < 0xe0 && $third < 0xc0 ) { - $this->assertEquals( - bin2hex( $head . UTF8_REPLACEMENT . UtfNormal::NFC( chr( $second ) . chr( $third ) . $tail ) ), - bin2hex( $clean ), - "Broken head + valid 2-byte $x" ); - } elseif( ( $first > 0xfd || $second > 0xfd ) && - ( ( $second > 0xbf && $third > 0xbf ) || - ( $second < 0xc0 && $third < 0xc0 ) || - ( $second > 0xfd ) || - ( $third > 0xfd ) ) ) { - # fe and ff are not legal head bytes -- expect three replacement chars - $this->assertEquals( - bin2hex( $head . UTF8_REPLACEMENT . UTF8_REPLACEMENT . UTF8_REPLACEMENT . $tail ), - bin2hex( $clean ), - "Forbidden triplet $x should be rejected" ); - } elseif( $first > 0xc2 && $second < 0xc0 && $third < 0xc0 ) { - $this->assertEquals( - bin2hex( $head . UTF8_REPLACEMENT . $tail ), - bin2hex( $clean ), - "Forbidden triplet $x should be rejected" ); - } else { - $this->assertEquals( - bin2hex( $head . UTF8_REPLACEMENT . UTF8_REPLACEMENT . $tail ), - bin2hex( $clean ), - "Forbidden triplet $x should be rejected" ); - } - } - } - } - } - - /** @todo document */ - function testChunkRegression() { - # Check for regression against a chunking bug - $text = "\x46\x55\xb8" . - "\xdc\x96" . - "\xee" . - "\xe7" . - "\x44" . - "\xaa" . - "\x2f\x25"; - $expect = "\x46\x55\xef\xbf\xbd" . - "\xdc\x96" . - "\xef\xbf\xbd" . - "\xef\xbf\xbd" . - "\x44" . - "\xef\xbf\xbd" . - "\x2f\x25"; - - $this->assertEquals( - bin2hex( $expect ), - bin2hex( UtfNormal::cleanUp( $text ) ) ); - } - - /** @todo document */ - function testInterposeRegression() { - $text = "\x4e\x30" . - "\xb1" . # bad tail - "\x3a" . - "\x92" . # bad tail - "\x62\x3a" . - "\x84" . # bad tail - "\x43" . - "\xc6" . # bad head - "\x3f" . - "\x92" . # bad tail - "\xad" . # bad tail - "\x7d" . - "\xd9\x95"; - - $expect = "\x4e\x30" . - "\xef\xbf\xbd" . - "\x3a" . - "\xef\xbf\xbd" . - "\x62\x3a" . - "\xef\xbf\xbd" . - "\x43" . - "\xef\xbf\xbd" . - "\x3f" . - "\xef\xbf\xbd" . - "\xef\xbf\xbd" . - "\x7d" . - "\xd9\x95"; - - $this->assertEquals( - bin2hex( $expect ), - bin2hex( UtfNormal::cleanUp( $text ) ) ); - } - - /** @todo document */ - function testOverlongRegression() { - $text = "\x67" . - "\x1a" . # forbidden ascii - "\xea" . # bad head - "\xc1\xa6" . # overlong sequence - "\xad" . # bad tail - "\x1c" . # forbidden ascii - "\xb0" . # bad tail - "\x3c" . - "\x9e"; # bad tail - $expect = "\x67" . - "\xef\xbf\xbd" . - "\xef\xbf\xbd" . - "\xef\xbf\xbd" . - "\xef\xbf\xbd" . - "\xef\xbf\xbd" . - "\xef\xbf\xbd" . - "\x3c" . - "\xef\xbf\xbd"; - $this->assertEquals( - bin2hex( $expect ), - bin2hex( UtfNormal::cleanUp( $text ) ) ); - } - - /** @todo document */ - function testSurrogateRegression() { - $text = "\xed\xb4\x96" . # surrogate 0xDD16 - "\x83" . # bad tail - "\xb4" . # bad tail - "\xac"; # bad head - $expect = "\xef\xbf\xbd" . - "\xef\xbf\xbd" . - "\xef\xbf\xbd" . - "\xef\xbf\xbd"; - $this->assertEquals( - bin2hex( $expect ), - bin2hex( UtfNormal::cleanUp( $text ) ) ); - } - - /** @todo document */ - function testBomRegression() { - $text = "\xef\xbf\xbe" . # U+FFFE, illegal char - "\xb2" . # bad tail - "\xef" . # bad head - "\x59"; - $expect = "\xef\xbf\xbd" . - "\xef\xbf\xbd" . - "\xef\xbf\xbd" . - "\x59"; - $this->assertEquals( - bin2hex( $expect ), - bin2hex( UtfNormal::cleanUp( $text ) ) ); - } - - /** @todo document */ - function testForbiddenRegression() { - $text = "\xef\xbf\xbf"; # U+FFFF, illegal char - $expect = "\xef\xbf\xbd"; - $this->assertEquals( - bin2hex( $expect ), - bin2hex( UtfNormal::cleanUp( $text ) ) ); - } - - /** @todo document */ - function testHangulRegression() { - $text = "\xed\x9c\xaf" . # Hangul char - "\xe1\x87\x81"; # followed by another final jamo - $expect = $text; # Should *not* change. - $this->assertEquals( - bin2hex( $expect ), - bin2hex( UtfNormal::cleanUp( $text ) ) ); - } -} diff --git a/tests/phpunit/includes/parser/MagicVariableTest.php b/tests/phpunit/includes/parser/MagicVariableTest.php deleted file mode 100644 index 31645313..00000000 --- a/tests/phpunit/includes/parser/MagicVariableTest.php +++ /dev/null @@ -1,201 +0,0 @@ -testParser = new Parser(); - $this->testParser->Options( new ParserOptions() ); - - # initialize parser output - $this->testParser->clearState(); - - # Needs a title to do magic word stuff - $title = Title::newFromText( 'Tests' ); - $title->mRedirect = false; # Else it needs a db connection just to check if it's a redirect (when deciding the page language) - - $this->testParser->setTitle( $title ); - } - - /** destroy parser (TODO: is it really neded?)*/ - function tearDown() { - unset( $this->testParser ); - } - - ############### TESTS ############################################# - # @todo FIXME: - # - those got copy pasted, we can probably make them cleaner - # - tests are lacking useful messages - - # day - - /** @dataProvider MediaWikiProvide::Days */ - function testCurrentdayIsUnPadded( $day ) { - $this->assertUnPadded( 'currentday', $day ); - } - /** @dataProvider MediaWikiProvide::Days */ - function testCurrentdaytwoIsZeroPadded( $day ) { - $this->assertZeroPadded( 'currentday2', $day ); - } - /** @dataProvider MediaWikiProvide::Days */ - function testLocaldayIsUnPadded( $day ) { - $this->assertUnPadded( 'localday', $day ); - } - /** @dataProvider MediaWikiProvide::Days */ - function testLocaldaytwoIsZeroPadded( $day ) { - $this->assertZeroPadded( 'localday2', $day ); - } - - # month - - /** @dataProvider MediaWikiProvide::Months */ - function testCurrentmonthIsZeroPadded( $month ) { - $this->assertZeroPadded( 'currentmonth', $month ); - } - /** @dataProvider MediaWikiProvide::Months */ - function testCurrentmonthoneIsUnPadded( $month ) { - $this->assertUnPadded( 'currentmonth1', $month ); - } - /** @dataProvider MediaWikiProvide::Months */ - function testLocalmonthIsZeroPadded( $month ) { - $this->assertZeroPadded( 'localmonth', $month ); - } - /** @dataProvider MediaWikiProvide::Months */ - function testLocalmonthoneIsUnPadded( $month ) { - $this->assertUnPadded( 'localmonth1', $month ); - } - - - # revision day - - /** @dataProvider MediaWikiProvide::Days */ - function testRevisiondayIsUnPadded( $day ) { - $this->assertUnPadded( 'revisionday', $day ); - } - /** @dataProvider MediaWikiProvide::Days */ - function testRevisiondaytwoIsZeroPadded( $day ) { - $this->assertZeroPadded( 'revisionday2', $day ); - } - - # revision month - - /** @dataProvider MediaWikiProvide::Months */ - function testRevisionmonthIsZeroPadded( $month ) { - $this->assertZeroPadded( 'revisionmonth', $month ); - } - /** @dataProvider MediaWikiProvide::Months */ - function testRevisionmonthoneIsUnPadded( $month ) { - $this->assertUnPadded( 'revisionmonth1', $month ); - } - - /** - * Rough tests for {{SERVERNAME}} magic word - * Bug 31176 - */ - function testServernameFromDifferentProtocols() { - global $wgServer; - $saved_wgServer= $wgServer; - - $wgServer = 'http://localhost/'; - $this->assertMagic( 'localhost', 'servername' ); - $wgServer = 'https://localhost/'; - $this->assertMagic( 'localhost', 'servername' ); - $wgServer = '//localhost/'; # bug 31176 - $this->assertMagic( 'localhost', 'servername' ); - - $wgServer = $saved_wgServer; - } - - ############### HELPERS ############################################ - - /** assertion helper expecting a magic output which is zero padded */ - PUBLIC function assertZeroPadded( $magic, $value ) { - $this->assertMagicPadding( $magic, $value, '%02d' ); - } - - /** assertion helper expecting a magic output which is unpadded */ - PUBLIC function assertUnPadded( $magic, $value ) { - $this->assertMagicPadding( $magic, $value, '%d' ); - } - - /** - * Main assertion helper for magic variables padding - * @param $magic string Magic variable name - * @param $value mixed Month or day - * @param $format string sprintf format for $value - */ - private function assertMagicPadding( $magic, $value, $format ) { - # Initialize parser timestamp as year 2010 at 12h34 56s. - # month and day are given by the caller ($value). Month < 12! - if( $value > 12 ) { $month = $value % 12; } - else { $month = $value; } - - $this->setParserTS( - sprintf( '2010%02d%02d123456', $month, $value ) - ); - - # please keep the following commented line of code. It helps debugging. - //print "\nDEBUG (value $value):" . sprintf( '2010%02d%02d123456', $value, $value ) . "\n"; - - # format expectation and test it - $expected = sprintf( $format, $value ); - $this->assertMagic( $expected, $magic ); - } - - /** helper to set the parser timestamp and revision timestamp */ - private function setParserTS( $ts ) { - $this->testParser->Options()->setTimestamp( $ts ); - $this->testParser->mRevisionTimestamp = $ts; - } - - /** - * Assertion helper to test a magic variable output - */ - private function assertMagic( $expected, $magic ) { - if( in_array( $magic, $this->expectedAsInteger ) ) { - $expected = (int) $expected; - } - - # Generate a message for the assertion - $msg = sprintf( "Magic %s should be <%s:%s>", - $magic, - $expected, - gettype( $expected ) - ); - - $this->assertSame( - $expected, - $this->testParser->getVariableValue( $magic ), - $msg - ); - } -} diff --git a/tests/phpunit/includes/parser/MediaWikiParserTest.php b/tests/phpunit/includes/parser/MediaWikiParserTest.php deleted file mode 100644 index 6a6fded1..00000000 --- a/tests/phpunit/includes/parser/MediaWikiParserTest.php +++ /dev/null @@ -1,36 +0,0 @@ - "\\'", '\\' => '\\\\' ) ) . "'; } " ); - - $parserTester = new $className( $testsName ); - $suite->addTestSuite( new ReflectionClass ( $parserTester ) ); - } - - - return $suite; - } -} diff --git a/tests/phpunit/includes/parser/NewParserTest.php b/tests/phpunit/includes/parser/NewParserTest.php deleted file mode 100644 index 69a96e66..00000000 --- a/tests/phpunit/includes/parser/NewParserTest.php +++ /dev/null @@ -1,895 +0,0 @@ -getCliArg( 'regex=' ) ) { - $this->regex = $this->getCliArg( 'regex=' ); - } else { - # Matches anything - $this->regex = ''; - } - - $this->keepUploads = $this->getCliArg( 'keep-uploads' ); - - $tmpGlobals = array(); - - $tmpGlobals['wgScript'] = '/index.php'; - $tmpGlobals['wgScriptPath'] = '/'; - $tmpGlobals['wgArticlePath'] = '/wiki/$1'; - $tmpGlobals['wgStyleSheetPath'] = '/skins'; - $tmpGlobals['wgStylePath'] = '/skins'; - $tmpGlobals['wgThumbnailScriptPath'] = false; - $tmpGlobals['wgLocalFileRepo'] = array( - 'class' => 'LocalRepo', - 'name' => 'local', - 'url' => 'http://example.com/images', - 'hashLevels' => 2, - 'transformVia404' => false, - 'backend' => 'local-backend' - ); - $tmpGlobals['wgForeignFileRepos'] = array(); - $tmpGlobals['wgEnableParserCache'] = false; - $tmpGlobals['wgHooks'] = $wgHooks; - $tmpGlobals['wgDeferredUpdateList'] = array(); - $tmpGlobals['wgMemc'] = wfGetMainCache(); - $tmpGlobals['messageMemc'] = wfGetMessageCacheStorage(); - $tmpGlobals['parserMemc'] = wfGetParserCacheStorage(); - - // $tmpGlobals['wgContLang'] = new StubContLang; - $tmpGlobals['wgUser'] = new User; - $context = new RequestContext(); - $tmpGlobals['wgLang'] = $context->getLanguage(); - $tmpGlobals['wgOut'] = $context->getOutput(); - $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) ); - $tmpGlobals['wgRequest'] = $context->getRequest(); - - if ( $GLOBALS['wgStyleDirectory'] === false ) { - $tmpGlobals['wgStyleDirectory'] = "$IP/skins"; - } - - - foreach ( $tmpGlobals as $var => $val ) { - if ( array_key_exists( $var, $GLOBALS ) ) { - $this->savedInitialGlobals[$var] = $GLOBALS[$var]; - } - - $GLOBALS[$var] = $val; - } - - $this->savedWeirdGlobals['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI]; - $this->savedWeirdGlobals['image_alias'] = $wgNamespaceAliases['Image']; - $this->savedWeirdGlobals['image_talk_alias'] = $wgNamespaceAliases['Image_talk']; - - $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface'; - $wgNamespaceAliases['Image'] = NS_FILE; - $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK; - } - - public function tearDown() { - foreach ( $this->savedInitialGlobals as $var => $val ) { - $GLOBALS[$var] = $val; - } - - global $wgNamespaceProtection, $wgNamespaceAliases; - - $wgNamespaceProtection[NS_MEDIAWIKI] = $this->savedWeirdGlobals['mw_namespace_protection']; - $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals['image_alias']; - $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals['image_talk_alias']; - - // Restore backends - RepoGroup::destroySingleton(); - FileBackendGroup::destroySingleton(); - } - - function addDBData() { - $this->tablesUsed[] = 'site_stats'; - $this->tablesUsed[] = 'interwiki'; - # disabled for performance - #$this->tablesUsed[] = 'image'; - - # Hack: insert a few Wikipedia in-project interwiki prefixes, - # for testing inter-language links - $this->db->insert( 'interwiki', array( - array( 'iw_prefix' => 'wikipedia', - 'iw_url' => 'http://en.wikipedia.org/wiki/$1', - 'iw_api' => '', - 'iw_wikiid' => '', - 'iw_local' => 0 ), - array( 'iw_prefix' => 'meatball', - 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1', - 'iw_api' => '', - 'iw_wikiid' => '', - 'iw_local' => 0 ), - array( 'iw_prefix' => 'zh', - 'iw_url' => 'http://zh.wikipedia.org/wiki/$1', - 'iw_api' => '', - 'iw_wikiid' => '', - 'iw_local' => 1 ), - array( 'iw_prefix' => 'es', - 'iw_url' => 'http://es.wikipedia.org/wiki/$1', - 'iw_api' => '', - 'iw_wikiid' => '', - 'iw_local' => 1 ), - array( 'iw_prefix' => 'fr', - 'iw_url' => 'http://fr.wikipedia.org/wiki/$1', - 'iw_api' => '', - 'iw_wikiid' => '', - 'iw_local' => 1 ), - array( 'iw_prefix' => 'ru', - 'iw_url' => 'http://ru.wikipedia.org/wiki/$1', - 'iw_api' => '', - 'iw_wikiid' => '', - 'iw_local' => 1 ), - /** - * @todo Fixme! Why are we inserting duplicate data here? Shouldn't - * need this IGNORE or shouldn't need the insert at all. - */ - ), __METHOD__, array( 'IGNORE' ) - ); - - - # Update certain things in site_stats - $this->db->insert( 'site_stats', - array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ), - __METHOD__ - ); - - # Reinitialise the LocalisationCache to match the database state - Language::getLocalisationCache()->unloadAll(); - - # Clear the message cache - MessageCache::singleton()->clear(); - - $user = User::newFromId( 0 ); - LinkCache::singleton()->clear(); # Avoids the odd failure at creating the nullRevision - - # Upload DB table entries for files. - # We will upload the actual files later. Note that if anything causes LocalFile::load() - # to be triggered before then, it will break via maybeUpgrade() setting the fileExists - # member to false and storing it in cache. - $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) ); - if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) { - $image->recordUpload2( - '', // archive name - 'Upload of some lame file', - 'Some lame file', - array( - 'size' => 12345, - 'width' => 1941, - 'height' => 220, - 'bits' => 24, - 'media_type' => MEDIATYPE_BITMAP, - 'mime' => 'image/jpeg', - 'metadata' => serialize( array() ), - 'sha1' => wfBaseConvert( '', 16, 36, 31 ), - 'fileExists' => true ), - $this->db->timestamp( '20010115123500' ), $user - ); - } - - # This image will be blacklisted in [[MediaWiki:Bad image list]] - $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) ); - if ( !$this->db->selectField( 'image', '1', array( 'img_name' => $image->getName() ) ) ) { - $image->recordUpload2( - '', // archive name - 'zomgnotcensored', - 'Borderline image', - array( - 'size' => 12345, - 'width' => 320, - 'height' => 240, - 'bits' => 24, - 'media_type' => MEDIATYPE_BITMAP, - 'mime' => 'image/jpeg', - 'metadata' => serialize( array() ), - 'sha1' => wfBaseConvert( '', 16, 36, 31 ), - 'fileExists' => true ), - $this->db->timestamp( '20010115123500' ), $user - ); - } - } - - - - - //ParserTest setup/teardown functions - - /** - * Set up the global variables for a consistent environment for each test. - * Ideally this should replace the global configuration entirely. - */ - protected function setupGlobals( $opts = '', $config = '' ) { - global $wgFileBackends; - # Find out values for some special options. - $lang = - self::getOptionValue( 'language', $opts, 'en' ); - $variant = - self::getOptionValue( 'variant', $opts, false ); - $maxtoclevel = - self::getOptionValue( 'wgMaxTocLevel', $opts, 999 ); - $linkHolderBatchSize = - self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 ); - - $uploadDir = $this->getUploadDir(); - if ( $this->getCliArg( 'use-filebackend=' ) ) { - if ( self::$backendToUse ) { - $backend = self::$backendToUse; - } else { - $name = $this->getCliArg( 'use-filebackend=' ); - $useConfig = array(); - foreach ( $wgFileBackends as $conf ) { - if ( $conf['name'] == $name ) { - $useConfig = $conf; - } - } - $useConfig['name'] = 'local-backend'; // swap name - $class = $conf['class']; - self::$backendToUse = new $class( $useConfig ); - $backend = self::$backendToUse; - } - } else { - $backend = new FSFileBackend( array( - 'name' => 'local-backend', - 'lockManager' => 'nullLockManager', - 'containerPaths' => array( - 'local-public' => "$uploadDir", - 'local-thumb' => "$uploadDir/thumb", - ) - ) ); - } - - $settings = array( - 'wgServer' => 'http://Britney-Spears', - 'wgScript' => '/index.php', - 'wgScriptPath' => '/', - 'wgArticlePath' => '/wiki/$1', - 'wgExtensionAssetsPath' => '/extensions', - 'wgActionPaths' => array(), - 'wgLocalFileRepo' => array( - 'class' => 'LocalRepo', - 'name' => 'local', - 'url' => 'http://example.com/images', - 'hashLevels' => 2, - 'transformVia404' => false, - 'backend' => $backend - ), - 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ), - 'wgStylePath' => '/skins', - 'wgStyleSheetPath' => '/skins', - 'wgSitename' => 'MediaWiki', - 'wgLanguageCode' => $lang, - 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_', - 'wgRawHtml' => isset( $opts['rawhtml'] ), - 'wgLang' => null, - 'wgContLang' => null, - 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ), - 'wgMaxTocLevel' => $maxtoclevel, - 'wgCapitalLinks' => true, - 'wgNoFollowLinks' => true, - 'wgNoFollowDomainExceptions' => array(), - 'wgThumbnailScriptPath' => false, - 'wgUseImageResize' => false, - 'wgUseTeX' => isset( $opts['math'] ), - 'wgMathDirectory' => $uploadDir . '/math', - 'wgLocaltimezone' => 'UTC', - 'wgAllowExternalImages' => true, - 'wgUseTidy' => false, - 'wgDefaultLanguageVariant' => $variant, - 'wgVariantArticlePath' => false, - 'wgGroupPermissions' => array( '*' => array( - 'createaccount' => true, - 'read' => true, - 'edit' => true, - 'createpage' => true, - 'createtalk' => true, - ) ), - 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ), - 'wgDefaultExternalStore' => array(), - 'wgForeignFileRepos' => array(), - 'wgLinkHolderBatchSize' => $linkHolderBatchSize, - 'wgExperimentalHtmlIds' => false, - 'wgExternalLinkTarget' => false, - 'wgAlwaysUseTidy' => false, - 'wgHtml5' => true, - 'wgWellFormedXml' => true, - 'wgAllowMicrodataAttributes' => true, - 'wgAdaptiveMessageCache' => true, - 'wgUseDatabaseMessages' => true, - ); - - if ( $config ) { - $configLines = explode( "\n", $config ); - - foreach ( $configLines as $line ) { - list( $var, $value ) = explode( '=', $line, 2 ); - - $settings[$var] = eval( "return $value;" ); //??? - } - } - - $this->savedGlobals = array(); - - /** @since 1.20 */ - wfRunHooks( 'ParserTestGlobals', array( &$settings ) ); - - foreach ( $settings as $var => $val ) { - if ( array_key_exists( $var, $GLOBALS ) ) { - $this->savedGlobals[$var] = $GLOBALS[$var]; - } - - $GLOBALS[$var] = $val; - } - - $langObj = Language::factory( $lang ); - $GLOBALS['wgContLang'] = $langObj; - $context = new RequestContext(); - $GLOBALS['wgLang'] = $context->getLanguage(); - - $GLOBALS['wgMemc'] = new EmptyBagOStuff; - $GLOBALS['wgOut'] = $context->getOutput(); - $GLOBALS['wgUser'] = $context->getUser(); - - global $wgHooks; - - $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup'; - $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp'; - - MagicWord::clearCache(); - RepoGroup::destroySingleton(); - FileBackendGroup::destroySingleton(); - - # Create dummy files in storage - $this->setupUploads(); - - # Publish the articles after we have the final language set - $this->publishTestArticles(); - - # The entries saved into RepoGroup cache with previous globals will be wrong. - RepoGroup::destroySingleton(); - FileBackendGroup::destroySingleton(); - MessageCache::destroyInstance(); - - return $context; - } - - /** - * Get an FS upload directory (only applies to FSFileBackend) - * - * @return String: the directory - */ - protected function getUploadDir() { - if ( $this->keepUploads ) { - $dir = wfTempDir() . '/mwParser-images'; - - if ( is_dir( $dir ) ) { - return $dir; - } - } else { - $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images"; - } - - // wfDebug( "Creating upload directory $dir\n" ); - if ( file_exists( $dir ) ) { - wfDebug( "Already exists!\n" ); - return $dir; - } - - return $dir; - } - - /** - * Create a dummy uploads directory which will contain a couple - * of files in order to pass existence tests. - * - * @return String: the directory - */ - protected function setupUploads() { - global $IP; - - $base = $this->getBaseDir(); - $backend = RepoGroup::singleton()->getLocalRepo()->getBackend(); - $backend->prepare( array( 'dir' => "$base/local-public/3/3a" ) ); - $backend->store( array( - 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/3/3a/Foobar.jpg" - ) ); - $backend->prepare( array( 'dir' => "$base/local-public/0/09" ) ); - $backend->store( array( - 'src' => "$IP/skins/monobook/headbg.jpg", 'dst' => "$base/local-public/0/09/Bad.jpg" - ) ); - } - - /** - * Restore default values and perform any necessary clean-up - * after each test runs. - */ - protected function teardownGlobals() { - $this->teardownUploads(); - - foreach ( $this->savedGlobals as $var => $val ) { - $GLOBALS[$var] = $val; - } - - RepoGroup::destroySingleton(); - LinkCache::singleton()->clear(); - } - - /** - * Remove the dummy uploads directory - */ - private function teardownUploads() { - if ( $this->keepUploads ) { - return; - } - - $base = $this->getBaseDir(); - // delete the files first, then the dirs. - self::deleteFiles( - array ( - "$base/local-public/3/3a/Foobar.jpg", - "$base/local-thumb/3/3a/Foobar.jpg/180px-Foobar.jpg", - "$base/local-thumb/3/3a/Foobar.jpg/200px-Foobar.jpg", - "$base/local-thumb/3/3a/Foobar.jpg/640px-Foobar.jpg", - "$base/local-thumb/3/3a/Foobar.jpg/120px-Foobar.jpg", - - "$base/local-public/0/09/Bad.jpg", - "$base/local-thumb/0/09/Bad.jpg", - - "$base/local-public/math/f/a/5/fa50b8b616463173474302ca3e63586b.png", - ) - ); - } - - /** - * Delete the specified files, if they exist. - * @param $files Array: full paths to files to delete. - */ - private static function deleteFiles( $files ) { - $backend = RepoGroup::singleton()->getLocalRepo()->getBackend(); - foreach ( $files as $file ) { - $backend->delete( array( 'src' => $file ), array( 'force' => 1 ) ); - } - foreach ( $files as $file ) { - $tmp = $file; - while ( $tmp = FileBackend::parentStoragePath( $tmp ) ) { - if ( !$backend->clean( array( 'dir' => $tmp ) )->isOK() ) { - break; - } - } - } - } - - protected function getBaseDir() { - return 'mwstore://local-backend'; - } - - public function parserTestProvider() { - if ( $this->file === false ) { - global $wgParserTestFiles; - $this->file = $wgParserTestFiles[0]; - } - return new TestFileIterator( $this->file, $this ); - } - - /** - * Set the file from whose tests will be run by this instance - */ - public function setParserTestFile( $filename ) { - $this->file = $filename; - } - - /** - * @group medium - * @dataProvider parserTestProvider - */ - public function testParserTest( $desc, $input, $result, $opts, $config ) { - if ( $this->regex != '' && !preg_match( '/' . $this->regex . '/', $desc ) ) { - $this->assertTrue( true ); // XXX: don't flood output with "test made no assertions" - //$this->markTestSkipped( 'Filtered out by the user' ); - return; - } - - wfDebug( "Running parser test: $desc\n" ); - - $opts = $this->parseOptions( $opts ); - $context = $this->setupGlobals( $opts, $config ); - - $user = $context->getUser(); - $options = ParserOptions::newFromContext( $context ); - - if ( isset( $opts['title'] ) ) { - $titleText = $opts['title']; - } - else { - $titleText = 'Parser test'; - } - - $local = isset( $opts['local'] ); - $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null; - $parser = $this->getParser( $preprocessor ); - - $title = Title::newFromText( $titleText ); - - if ( isset( $opts['pst'] ) ) { - $out = $parser->preSaveTransform( $input, $title, $user, $options ); - } elseif ( isset( $opts['msg'] ) ) { - $out = $parser->transformMsg( $input, $options, $title ); - } elseif ( isset( $opts['section'] ) ) { - $section = $opts['section']; - $out = $parser->getSection( $input, $section ); - } elseif ( isset( $opts['replace'] ) ) { - $section = $opts['replace'][0]; - $replace = $opts['replace'][1]; - $out = $parser->replaceSection( $input, $section, $replace ); - } elseif ( isset( $opts['comment'] ) ) { - $out = Linker::formatComment( $input, $title, $local ); - } elseif ( isset( $opts['preload'] ) ) { - $out = $parser->getpreloadText( $input, $title, $options ); - } else { - $output = $parser->parse( $input, $title, $options, true, true, 1337 ); - $out = $output->getText(); - - if ( isset( $opts['showtitle'] ) ) { - if ( $output->getTitleText() ) { - $title = $output->getTitleText(); - } - - $out = "$title\n$out"; - } - - if ( isset( $opts['ill'] ) ) { - $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) ); - } elseif ( isset( $opts['cat'] ) ) { - $outputPage = $context->getOutput(); - $outputPage->addCategoryLinks( $output->getCategories() ); - $cats = $outputPage->getCategoryLinks(); - - if ( isset( $cats['normal'] ) ) { - $out = $this->tidy( implode( ' ', $cats['normal'] ) ); - } else { - $out = ''; - } - } - $parser->mPreprocessor = null; - - $result = $this->tidy( $result ); - } - - $this->teardownGlobals(); - - $this->assertEquals( $result, $out, $desc ); - } - - /** - * Run a fuzz test series - * Draw input from a set of test files - * - * @todo fixme Needs some work to not eat memory until the world explodes - * - * @group ParserFuzz - */ - function testFuzzTests() { - global $wgParserTestFiles; - - $files = $wgParserTestFiles; - - if( $this->getCliArg( 'file=' ) ) { - $files = array( $this->getCliArg( 'file=' ) ); - } - - $dict = $this->getFuzzInput( $files ); - $dictSize = strlen( $dict ); - $logMaxLength = log( $this->maxFuzzTestLength ); - - ini_set( 'memory_limit', $this->memoryLimit * 1048576 ); - - $user = new User; - $opts = ParserOptions::newFromUser( $user ); - $title = Title::makeTitle( NS_MAIN, 'Parser_test' ); - - $id = 1; - - while ( true ) { - - // Generate test input - mt_srand( ++$this->fuzzSeed ); - $totalLength = mt_rand( 1, $this->maxFuzzTestLength ); - $input = ''; - - while ( strlen( $input ) < $totalLength ) { - $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength; - $hairLength = min( intval( exp( $logHairLength ) ), $dictSize ); - $offset = mt_rand( 0, $dictSize - $hairLength ); - $input .= substr( $dict, $offset, $hairLength ); - } - - $this->setupGlobals(); - $parser = $this->getParser(); - - // Run the test - try { - $parser->parse( $input, $title, $opts ); - $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" ); - } catch ( Exception $exception ) { - $input_dump = sprintf( "string(%d) \"%s\"\n", strlen( $input ), $input ); - - $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" ); - } - - $this->teardownGlobals(); - $parser->__destruct(); - - if ( $id % 100 == 0 ) { - $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 ); - //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n"; - if ( $usage > 90 ) { - $ret = "Out of memory:\n"; - $memStats = $this->getMemoryBreakdown(); - - foreach ( $memStats as $name => $usage ) { - $ret .= "$name: $usage\n"; - } - - throw new MWException( $ret ); - } - } - - $id++; - - } - } - - //Various getter functions - - /** - * Get an input dictionary from a set of parser test files - */ - function getFuzzInput( $filenames ) { - $dict = ''; - - foreach ( $filenames as $filename ) { - $contents = file_get_contents( $filename ); - preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches ); - - foreach ( $matches[1] as $match ) { - $dict .= $match . "\n"; - } - } - - return $dict; - } - - /** - * Get a memory usage breakdown - */ - function getMemoryBreakdown() { - $memStats = array(); - - foreach ( $GLOBALS as $name => $value ) { - $memStats['$' . $name] = strlen( serialize( $value ) ); - } - - $classes = get_declared_classes(); - - foreach ( $classes as $class ) { - $rc = new ReflectionClass( $class ); - $props = $rc->getStaticProperties(); - $memStats[$class] = strlen( serialize( $props ) ); - $methods = $rc->getMethods(); - - foreach ( $methods as $method ) { - $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) ); - } - } - - $functions = get_defined_functions(); - - foreach ( $functions['user'] as $function ) { - $rf = new ReflectionFunction( $function ); - $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) ); - } - - asort( $memStats ); - - return $memStats; - } - - /** - * Get a Parser object - */ - function getParser( $preprocessor = null ) { - global $wgParserConf; - - $class = $wgParserConf['class']; - $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf ); - - wfRunHooks( 'ParserTestParser', array( &$parser ) ); - - return $parser; - } - - //Various action functions - - public function addArticle( $name, $text, $line ) { - self::$articles[$name] = array( $text, $line ); - } - - public function publishTestArticles() { - if ( empty( self::$articles ) ) { - return; - } - - foreach ( self::$articles as $name => $info ) { - list( $text, $line ) = $info; - ParserTest::addArticle( $name, $text, $line, 'ignoreduplicate' ); - } - } - - /** - * Steal a callback function from the primary parser, save it for - * application to our scary parser. If the hook is not installed, - * abort processing of this file. - * - * @param $name String - * @return Bool true if tag hook is present - */ - public function requireHook( $name ) { - global $wgParser; - $wgParser->firstCallInit( ); // make sure hooks are loaded. - return isset( $wgParser->mTagHooks[$name] ); - } - - public function requireFunctionHook( $name ) { - global $wgParser; - $wgParser->firstCallInit( ); // make sure hooks are loaded. - return isset( $wgParser->mFunctionHooks[$name] ); - } - //Various "cleanup" functions - - /** - * Run the "tidy" command on text if the $wgUseTidy - * global is true - * - * @param $text String: the text to tidy - * @return String - */ - protected function tidy( $text ) { - global $wgUseTidy; - - if ( $wgUseTidy ) { - $text = MWTidy::tidy( $text ); - } - - return $text; - } - - /** - * Remove last character if it is a newline - */ - public function removeEndingNewline( $s ) { - if ( substr( $s, -1 ) === "\n" ) { - return substr( $s, 0, -1 ); - } - else { - return $s; - } - } - - //Test options parser functions - - protected function parseOptions( $instring ) { - $opts = array(); - // foo - // foo=bar - // foo="bar baz" - // foo=[[bar baz]] - // foo=bar,"baz quux" - $regex = '/\b - ([\w-]+) # Key - \b - (?:\s* - = # First sub-value - \s* - ( - " - [^"]* # Quoted val - " - | - \[\[ - [^]]* # Link target - \]\] - | - [\w-]+ # Plain word - ) - (?:\s* - , # Sub-vals 1..N - \s* - ( - "[^"]*" # Quoted val - | - \[\[[^]]*\]\] # Link target - | - [\w-]+ # Plain word - ) - )* - )? - /x'; - - if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) { - foreach ( $matches as $bits ) { - array_shift( $bits ); - $key = strtolower( array_shift( $bits ) ); - if ( count( $bits ) == 0 ) { - $opts[$key] = true; - } elseif ( count( $bits ) == 1 ) { - $opts[$key] = $this->cleanupOption( array_shift( $bits ) ); - } else { - // Array! - $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits ); - } - } - } - return $opts; - } - - protected function cleanupOption( $opt ) { - if ( substr( $opt, 0, 1 ) == '"' ) { - return substr( $opt, 1, -1 ); - } - - if ( substr( $opt, 0, 2 ) == '[[' ) { - return substr( $opt, 2, -2 ); - } - return $opt; - } - - /** - * Use a regex to find out the value of an option - * @param $key String: name of option val to retrieve - * @param $opts Options array to look in - * @param $default Mixed: default value returned if not found - */ - protected static function getOptionValue( $key, $opts, $default ) { - $key = strtolower( $key ); - - if ( isset( $opts[$key] ) ) { - return $opts[$key]; - } else { - return $default; - } - } -} diff --git a/tests/phpunit/includes/parser/ParserMethodsTest.php b/tests/phpunit/includes/parser/ParserMethodsTest.php deleted file mode 100644 index dea406c3..00000000 --- a/tests/phpunit/includes/parser/ParserMethodsTest.php +++ /dev/null @@ -1,33 +0,0 @@ -~~~', - 'hello \'\'this\'\' is ~~~', - ), - ); - } - - /** - * @dataProvider dataPreSaveTransform - */ - public function testPreSaveTransform( $text, $expected ) { - global $wgParser; - - $title = Title::newFromText( str_replace( '::', '__', __METHOD__ ) ); - $user = new User(); - $user->setName( "127.0.0.1" ); - $popts = ParserOptions::newFromUser( $user ); - $text = $wgParser->preSaveTransform( $text, $title, $user, $popts ); - - $this->assertEquals( $expected, $text ); - } - - // TODO: Add tests for cleanSig() / cleanSigInSig(), getSection(), replaceSection(), getPreloadText() -} - diff --git a/tests/phpunit/includes/parser/ParserPreloadTest.php b/tests/phpunit/includes/parser/ParserPreloadTest.php deleted file mode 100644 index 0e8ef530..00000000 --- a/tests/phpunit/includes/parser/ParserPreloadTest.php +++ /dev/null @@ -1,67 +0,0 @@ -testParserOptions = new ParserOptions(); - - $this->testParser = new Parser(); - $this->testParser->Options( $this->testParserOptions ); - $this->testParser->clearState(); - - $this->title = Title::newFromText( 'Preload Test' ); - } - - function tearDown() { - unset( $this->testParser ); - unset( $this->title ); - } - - /** - * @covers Parser::getPreloadText - */ - function testPreloadSimpleText() { - $this->assertPreloaded( 'simple', 'simple' ); - } - - /** - * @covers Parser::getPreloadText - */ - function testPreloadedPreIsUnstripped() { - $this->assertPreloaded( - '
monospaced
', - '
monospaced
', - '
 in preloaded text must be unstripped (bug 27467)'
-		);
-	}
-
-	/**
-	 * @covers Parser::getPreloadText
-	 */
-	function testPreloadedNowikiIsUnstripped() {
-		$this->assertPreloaded(
-			'[[Dummy title]]',
-			'[[Dummy title]]',
-			' in preloaded text must be unstripped (bug 27467)'
-		);
-	}
-
-	function assertPreloaded( $expected, $text, $msg='') {
-		$this->assertEquals(
-			$expected,
-			$this->testParser->getPreloadText(
-				$text,
-				$this->title,
-				$this->testParserOptions
-			),
-			$msg
-		);
-	}
-
-}
diff --git a/tests/phpunit/includes/parser/PreprocessorTest.php b/tests/phpunit/includes/parser/PreprocessorTest.php
deleted file mode 100644
index fee56748..00000000
--- a/tests/phpunit/includes/parser/PreprocessorTest.php
+++ /dev/null
@@ -1,233 +0,0 @@
-mOptions = new ParserOptions();
-		$name = isset( $wgParserConf['preprocessorClass'] ) ? $wgParserConf['preprocessorClass'] : 'Preprocessor_DOM';
-
-		$this->mPreprocessor = new $name( $this );
-	}
-
-	function getStripList() {
-		return array( 'gallery', 'display map' /* Used by Maps, see r80025 CR */, '/foo' );
-	}
-
-	function provideCases() {
-		return array(
-			array( "Foo", "Foo" ),
-			array( "", "<!-- Foo -->" ),
-			array( "", "<!-- Foo --><!-- Bar -->" ),
-			array( "  ", "<!-- Foo -->  <!-- Bar -->" ),
-			array( " \n ", "<!-- Foo --> \n <!-- Bar -->" ),
-			array( " \n \n", "<!-- Foo --> \n <!-- Bar -->\n" ),
-			array( "  \n", "<!-- Foo -->  <!-- Bar -->\n" ),
-			array( "Bar", "<!-->Bar" ),
-			array( "\n== Baz ==\n", "== Foo ==\n  <!-- Bar -->\n== Baz ==\n" ),
-			array( "", "gallery" ),
-			array( "Foo  Bar", "Foo gallery Bar" ),
-			array( "", "gallery</gallery>" ),
-			array( " ", "<foo> gallery</gallery>" ),
-			array( " ", "<foo> gallery<gallery></gallery>" ),
-			array( " Foo bar ", "<noinclude> Foo bar </noinclude>" ),
-			array( "\n{{Foo}}\n", "<noinclude>\n\n</noinclude>" ),
-			array( "\n{{Foo}}\n\n", "<noinclude>\n\n</noinclude>\n" ),
-			array( "foo bar", "galleryfoo bar" ),
-			array( "<{{foo}}>", "<>" ),
-			array( "<{{{foo}}}>", "<foo>" ),
-			array( "", "gallery</gallery</gallery>" ),
-			array( "=== Foo === ", "=== Foo === " ),
-			array( "=== Foo === ", "==<!-- -->= Foo === " ),
-			array( "=== Foo === ", "=== Foo ==<!-- -->= " ),
-			array( "=== Foo ===\n", "=== Foo ===<!-- -->\n" ),
-			array( "=== Foo === \n", "=== Foo ===<!-- --> <!-- -->\n" ),
-			array( "== Foo ==\n== Bar == \n", "== Foo ==\n== Bar == \n" ),
-			array( "===========", "===========" ),
-			array( "Foo\n=\n==\n=\n", "Foo\n=\n==\n=\n" ),
-			array( "{{Foo}}", "" ),
-			array( "\n{{Foo}}", "\n" ),
-			array( "{{Foo|bar}}", "" ),  
-			array( "{{Foo|bar}}a", "a" ),  
-			array( "{{Foo|bar|baz}}", "" ),  
-			array( "{{Foo|1=bar}}", "" ),
-			array( "{{Foo|=bar}}", "" ),
-			array( "{{Foo|bar=baz}}", "" ), 
-			array( "{{Foo|{{bar}}=baz}}", "" ),
-			array( "{{Foo|1=bar|baz}}", "" ), 
-			array( "{{Foo|1=bar|2=baz}}", "" ),
-			array( "{{Foo|bar|foo=baz}}", "" ), 
-			array( "{{{1}}}", "1" ),
-			array( "{{{1|}}}", "1" ),
-			array( "{{{Foo}}}", "Foo" ),
-			array( "{{{Foo|}}}", "Foo" ),
-			array( "{{{Foo|bar|baz}}}", "Foobarbaz" ),
-			array( "{{Foo}}", "{<!-- -->{Foo}}" ),
-			array( "{{{{Foobar}}}}", "{Foobar}" ),
-			array( "{{{ {{Foo}} }}}", " <template><title>Foo " ),
-			array( "{{ {{{Foo}}} }}", "" ),
-			array( "{{{{{Foo}}}}}", "" ),
-			array( "{{{{{Foo}} }}}", "<template><title>Foo " ),
-			array( "{{{{{{Foo}}}}}}", "<tplarg><title>Foo" ),
-			array( "{{{{{{Foo}}}}}", "{" ),
-			array( "[[[Foo]]", "[[[Foo]]" ),
-			array( "{{Foo|[[[[bar]]|baz]]}}", "" ), // This test is important, since it means the difference between having the [[ rule stacked or not
-			array( "{{Foo|[[[[bar]|baz]]}}", "{{Foo|[[[[bar]|baz]]}}" ),
-			array( "{{Foo|Foo [[[[bar]|baz]]}}", "{{Foo|Foo [[[[bar]|baz]]}}" ),
-			array( "Foo BarBaz", "Foo display mapBar</display map             >Baz" ),
-			array( "Foo BarBaz", "Foo display map fooBar</display map             >Baz" ),
-			array( "Foo ", "Foo gallery bar="baz" " ),
-			array( "Foo ", "Foo gallery bar="1" baz=2 " ),
-			array( "Foo", "/fooFoo<//foo>" ), # Worth blacklisting IMHO
-			array( "{{#ifexpr: ({{{1|1}}} = 2) | Foo | Bar }}", ""),
-			array( "{{#if: {{{1|}}} | Foo | {{Bar}} }}", ""),
-			array( "{{#if: {{{1|}}} | Foo | [[Bar]] }}", ""),
-			array( "{{#if: {{{1|}}} | [[Foo]] | Bar }}", ""),
-			array( "{{#if: {{{1|}}} | 1 | {{#if: {{{1|}}} | 2 | 3 }} }}", ""),
-			array( "{{ {{Foo}}", "{{ "),
-			array( "{{Foobar {{Foo}} {{Bar}} {{Baz}} ", "{{Foobar    "),
-			array( "[[Foo]] |", "[[Foo]] |"),
-			array( "{{Foo|Bar|", "{{Foo|Bar|"),
-			array( "[[Foo]", "[[Foo]"),
-			array( "[[Foo|Bar]", "[[Foo|Bar]"),
-			array( "{{Foo| [[Bar] }}", "{{Foo| [[Bar] }}"),
-			array( "{{Foo| [[Bar|Baz] }}", "{{Foo| [[Bar|Baz] }}"),
-			array( "{{Foo|bar=[[baz]}}", "{{Foo|bar=[[baz]}}"),
-			array( "{{foo|", "{{foo|"),
-			array( "{{foo|}", "{{foo|}"),
-			array( "{{foo|} }}", ""),
-			array( "{{foo|bar=|}", "{{foo|bar=|}"),
-			array( "{{Foo|} Bar=", "{{Foo|} Bar="),
-			array( "{{Foo|} Bar=}}", ""),
-			/* array( file_get_contents( __DIR__ . '/QuoteQuran.txt' ), file_get_contents( __DIR__ . '/QuoteQuranExpanded.txt' ) ), */
-		);
-	}
-
-	/**
-	 * Get XML preprocessor tree from the preprocessor (which may not be the
-	 * native XML-based one).
-	 *
-	 * @param string $wikiText
-	 * @return string
-	 */
-	function preprocessToXml( $wikiText ) {
-		if ( method_exists( $this->mPreprocessor, 'preprocessToXml' ) ) {
-			return $this->normalizeXml( $this->mPreprocessor->preprocessToXml( $wikiText ) );
-		}
-		
-		$dom = $this->mPreprocessor->preprocessToObj( $wikiText );
-		if ( is_callable( array( $dom, 'saveXML' ) ) ) {
-			return $dom->saveXML();
-		} else {
-			return $this->normalizeXml( $dom->__toString() );
-		}
-	}
-
-	/**
-	 * Normalize XML string to the form that a DOMDocument saves out.
-	 *
-	 * @param string $xml
-	 * @return string
-	 */
-	function normalizeXml( $xml ) {
-		return preg_replace( '!<([a-z]+)/>!', '<$1>', str_replace( ' />', '/>', $xml ) );
-		
-		$dom = new DOMDocument();
-		// 1 << 19 == XML_PARSE_HUGE, needed so newer versions of libxml2 don't barf when the XML is >256 levels deep
-		$dom->loadXML( $xml, 1 << 19 );
-		return $dom->saveXML();
-	}
-
-	/**
-	 * @dataProvider provideCases
-	 */
-	function testPreprocessorOutput( $wikiText, $expectedXml ) {
-		$this->assertEquals( $this->normalizeXml( $expectedXml ), $this->preprocessToXml( $wikiText ) );
-	}
-
-	/**
-	 * These are more complex test cases taken out of wiki articles.
-	 */
-	function provideFiles() {
-		return array(
-			array( "QuoteQuran" ), # http://en.wikipedia.org/w/index.php?title=Template:QuoteQuran/sandbox&oldid=237348988 GFDL + CC-BY-SA by Striver
-			array( "Factorial" ), # http://en.wikipedia.org/w/index.php?title=Template:Factorial&oldid=98548758 GFDL + CC-BY-SA by Polonium
-			array( "All_system_messages" ), # http://tl.wiktionary.org/w/index.php?title=Suleras:All_system_messages&oldid=2765 GPL text generated by MediaWiki
-			array( "Fundraising" ), # http://tl.wiktionary.org/w/index.php?title=MediaWiki:Sitenotice&oldid=5716 GFDL + CC-BY-SA, copied there by Sky Harbor.
-		);
-	}
-
-	/**
-	 * @dataProvider provideFiles
-	 */
-	function testPreprocessorOutputFiles( $filename ) {
-		$folder = __DIR__ . "/../../../parser/preprocess";
-		$wikiText = file_get_contents( "$folder/$filename.txt" );
-		$output = $this->preprocessToXml( $wikiText );
-
-		$expectedFilename = "$folder/$filename.expected";
-		if ( file_exists( $expectedFilename ) ) {
-			$expectedXml = $this->normalizeXml( file_get_contents( $expectedFilename ) );
-			$this->assertEquals( $expectedXml, $output );
-		} else {
-			$tempFilename = tempnam( $folder, "$filename." );
-			file_put_contents( $tempFilename, $output );
-			$this->markTestIncomplete( "File $expectedFilename missing. Output stored as $tempFilename" );
-		}
-	}
-
-	/**
-	 * Tests from Bug 28642 · https://bugzilla.wikimedia.org/28642
-	 */
-	function provideHeadings() {
-		return array(	/* These should become headings: */
-			array( "== h ==", "== h ==<!--c1-->" ),
-			array( "== h == 	", "== h == 	<!--c1-->" ),
-			array( "== h == 	", "== h ==<!--c1--> 	" ),
-			array( "== h == 	 	", "== h == 	<!--c1--> 	" ),
-			array( "== h ==", "== h ==<!--c1--><!--c2-->" ),
-			array( "== h == 	", "== h == 	<!--c1--><!--c2-->" ),
-			array( "== h == 	", "== h ==<!--c1--><!--c2--> 	" ),
-			array( "== h == 	 	", "== h == 	<!--c1--><!--c2--> 	" ),
-			array( "== h == 	  ", "== h == 	<!--c1-->  <!--c2-->" ),
-			array( "== h ==   	", "== h ==<!--c1-->  <!--c2--> 	" ),
-			array( "== h == 	   	", "== h == 	<!--c1-->  <!--c2--> 	" ),
-			array( "== h ==", "== h ==<!--c1--><!--c2--><!--c3-->" ),
-			array( "== h ==  ", "== h ==<!--c1-->  <!--c2--><!--c3-->" ),
-			array( "== h ==  ", "== h ==<!--c1--><!--c2-->  <!--c3-->" ),
-			array( "== h ==    ", "== h ==<!--c1-->  <!--c2-->  <!--c3-->" ),
-			array( "== h ==  ", "== h ==  <!--c1--><!--c2--><!--c3-->" ),
-			array( "== h ==    ", "== h ==  <!--c1-->  <!--c2--><!--c3-->" ),
-			array( "== h ==    ", "== h ==  <!--c1--><!--c2-->  <!--c3-->" ),
-			array( "== h ==      ", "== h ==  <!--c1-->  <!--c2-->  <!--c3-->" ),
-			array( "== h ==  ", "== h ==<!--c1--><!--c2--><!--c3-->  " ),
-			array( "== h ==    ", "== h ==<!--c1-->  <!--c2--><!--c3-->  " ),
-			array( "== h ==    ", "== h ==<!--c1--><!--c2-->  <!--c3-->  " ),
-			array( "== h ==      ", "== h ==<!--c1-->  <!--c2-->  <!--c3-->  " ),
-			array( "== h ==    ", "== h ==  <!--c1--><!--c2--><!--c3-->  " ),
-			array( "== h ==      ", "== h ==  <!--c1-->  <!--c2--><!--c3-->  " ),
-			array( "== h ==      ", "== h ==  <!--c1--><!--c2-->  <!--c3-->  " ),
-			array( "== h ==        ", "== h ==  <!--c1-->  <!--c2-->  <!--c3-->  " ),
-
-			/* These are not working: */
-			array( "== h == 	", "== h ==<!--c1--> 	<!--c2-->" ),
-			array( "== h == 	 	", "== h == 	<!--c1--> 	<!--c2-->" ),
-			array( "== h == 	 	", "== h ==<!--c1--> 	<!--c2--> 	" ),
-			array( "== h == x   ", "== h == x <!--c1--><!--c2--><!--c3-->  " ),
-			array( "== h == x   ", "== h ==<!--c1--> x <!--c2--><!--c3-->  " ),
-			array( "== h == x ", "== h ==<!--c1--><!--c2--><!--c3--> x " ),
-		);
-	}
-
-	/**
-	 * @dataProvider provideHeadings
-	 */
-	function testHeadings( $wikiText, $expectedXml ) {
-		$this->assertEquals( $this->normalizeXml( $expectedXml ), $this->preprocessToXml( $wikiText ) );
-	}
-}
-
diff --git a/tests/phpunit/includes/parser/TagHooksTest.php b/tests/phpunit/includes/parser/TagHooksTest.php
deleted file mode 100644
index 713ce846..00000000
--- a/tests/phpunit/includes/parser/TagHooksTest.php
+++ /dev/null
@@ -1,77 +0,0 @@
-bar" ), array( "foo\nbar" ),  array( "foo\rbar" ) );
-	}
-		
-	/**
-	 * @dataProvider provideValidNames
-	 */
-	function testTagHooks( $tag ) {
-		global $wgParserConf;
-		$parser = new Parser( $wgParserConf );
-		
-		$parser->setHook( $tag, array( $this, 'tagCallback' ) );
-		$parserOutput = $parser->parse( "Foo<$tag>BarBaz", Title::newFromText( 'Test' ), new ParserOptions );
-		$this->assertEquals( "

FooOneBaz\n

", $parserOutput->getText() ); - - $parser->mPreprocessor = null; # Break the Parser <-> Preprocessor cycle - } - - /** - * @dataProvider provideBadNames - * @expectedException MWException - */ - function testBadTagHooks( $tag ) { - global $wgParserConf; - $parser = new Parser( $wgParserConf ); - - $parser->setHook( $tag, array( $this, 'tagCallback' ) ); - $parser->parse( "Foo<$tag>BarBaz", Title::newFromText( 'Test' ), new ParserOptions ); - $this->fail('Exception not thrown.'); - } - - /** - * @dataProvider provideValidNames - */ - function testFunctionTagHooks( $tag ) { - global $wgParserConf; - $parser = new Parser( $wgParserConf ); - - $parser->setFunctionTagHook( $tag, array( $this, 'functionTagCallback' ), 0 ); - $parserOutput = $parser->parse( "Foo<$tag>BarBaz", Title::newFromText( 'Test' ), new ParserOptions ); - $this->assertEquals( "

FooOneBaz\n

", $parserOutput->getText() ); - - $parser->mPreprocessor = null; # Break the Parser <-> Preprocessor cycle - } - - /** - * @dataProvider provideBadNames - * @expectedException MWException - */ - function testBadFunctionTagHooks( $tag ) { - global $wgParserConf; - $parser = new Parser( $wgParserConf ); - - $parser->setFunctionTagHook( $tag, array( $this, 'functionTagCallback' ), SFH_OBJECT_ARGS ); - $parser->parse( "Foo<$tag>BarBaz", Title::newFromText( 'Test' ), new ParserOptions ); - $this->fail('Exception not thrown.'); - } - - function tagCallback( $text, $params, $parser ) { - return str_rot13( $text ); - } - - function functionTagCallback( &$parser, $frame, $code, $attribs ) { - return str_rot13( $code ); - } -} diff --git a/tests/phpunit/includes/search/SearchEngineTest.php b/tests/phpunit/includes/search/SearchEngineTest.php deleted file mode 100644 index 957907c7..00000000 --- a/tests/phpunit/includes/search/SearchEngineTest.php +++ /dev/null @@ -1,163 +0,0 @@ -search ); - } - - /** - * Checks for database type & version. - * Will skip current test if DB does not support search. - */ - function setUp() { - parent::setUp(); - // Search tests require MySQL or SQLite with FTS - # Get database type and version - $dbType = $this->db->getType(); - $dbSupported = - ($dbType === 'mysql') - || ( $dbType === 'sqlite' && $this->db->getFulltextSearchModule() == 'FTS3' ); - - if( !$dbSupported ) { - $this->markTestSkipped( "MySQL or SQLite with FTS3 only" ); - } - - $searchType = $this->db->getSearchEngine(); - $this->search = new $searchType( $this->db ); - } - - function pageExists( $title ) { - return false; - } - - function addDBData() { - if ( $this->pageExists( 'Not_Main_Page' ) ) { - return; - } - $this->insertPage( "Not_Main_Page", "This is not a main page", 0 ); - $this->insertPage( 'Talk:Not_Main_Page', 'This is not a talk page to the main page, see [[smithee]]', 1 ); - $this->insertPage( 'Smithee', 'A smithee is one who smiths. See also [[Alan Smithee]]', 0 ); - $this->insertPage( 'Talk:Smithee', 'This article sucks.', 1 ); - $this->insertPage( 'Unrelated_page', 'Nothing in this page is about the S word.', 0 ); - $this->insertPage( 'Another_page', 'This page also is unrelated.', 0 ); - $this->insertPage( 'Help:Help', 'Help me!', 4 ); - $this->insertPage( 'Thppt', 'Blah blah', 0 ); - $this->insertPage( 'Alan_Smithee', 'yum', 0 ); - $this->insertPage( 'Pages', 'are\'food', 0 ); - $this->insertPage( 'HalfOneUp', 'AZ', 0 ); - $this->insertPage( 'FullOneUp', 'AZ', 0 ); - $this->insertPage( 'HalfTwoLow', 'az', 0 ); - $this->insertPage( 'FullTwoLow', 'az', 0 ); - $this->insertPage( 'HalfNumbers', '1234567890', 0 ); - $this->insertPage( 'FullNumbers', '1234567890', 0 ); - $this->insertPage( 'DomainName', 'example.com', 0 ); - } - - function fetchIds( $results ) { - $this->assertTrue( is_object( $results ) ); - - $matches = array(); - $row = $results->next(); - while ( $row ) { - $matches[] = $row->getTitle()->getPrefixedText(); - $row = $results->next(); - } - $results->free(); - # Search is not guaranteed to return results in a certain order; - # sort them numerically so we will compare simply that we received - # the expected matches. - sort( $matches ); - return $matches; - } - - /** - * Insert a new page - * - * @param $pageName String: page name - * @param $text String: page's content - * @param $n Integer: unused - */ - function insertPage( $pageName, $text, $ns ) { - $title = Title::newFromText( $pageName ); - - $user = User::newFromName( 'WikiSysop' ); - $comment = 'Search Test'; - - // avoid memory leak...? - LinkCache::singleton()->clear(); - - $page = WikiPage::factory( $title ); - $page->doEdit( $text, $comment, 0, false, $user ); - - $this->pageList[] = array( $title, $page->getId() ); - - return true; - } - - function testFullWidth() { - $this->assertEquals( - array( 'FullOneUp', 'FullTwoLow', 'HalfOneUp', 'HalfTwoLow' ), - $this->fetchIds( $this->search->searchText( 'AZ' ) ), - "Search for normalized from Half-width Upper" ); - $this->assertEquals( - array( 'FullOneUp', 'FullTwoLow', 'HalfOneUp', 'HalfTwoLow' ), - $this->fetchIds( $this->search->searchText( 'az' ) ), - "Search for normalized from Half-width Lower" ); - $this->assertEquals( - array( 'FullOneUp', 'FullTwoLow', 'HalfOneUp', 'HalfTwoLow' ), - $this->fetchIds( $this->search->searchText( 'AZ' ) ), - "Search for normalized from Full-width Upper" ); - $this->assertEquals( - array( 'FullOneUp', 'FullTwoLow', 'HalfOneUp', 'HalfTwoLow' ), - $this->fetchIds( $this->search->searchText( 'az' ) ), - "Search for normalized from Full-width Lower" ); - } - - function testTextSearch() { - $this->assertEquals( - array( 'Smithee' ), - $this->fetchIds( $this->search->searchText( 'smithee' ) ), - "Plain search failed" ); - } - - function testTextPowerSearch() { - $this->search->setNamespaces( array( 0, 1, 4 ) ); - $this->assertEquals( - array( - 'Smithee', - 'Talk:Not Main Page', - ), - $this->fetchIds( $this->search->searchText( 'smithee' ) ), - "Power search failed" ); - } - - function testTitleSearch() { - $this->assertEquals( - array( - 'Alan Smithee', - 'Smithee', - ), - $this->fetchIds( $this->search->searchTitle( 'smithee' ) ), - "Title search failed" ); - } - - function testTextTitlePowerSearch() { - $this->search->setNamespaces( array( 0, 1, 4 ) ); - $this->assertEquals( - array( - 'Alan Smithee', - 'Smithee', - 'Talk:Smithee', - ), - $this->fetchIds( $this->search->searchTitle( 'smithee' ) ), - "Title power search failed" ); - } - -} diff --git a/tests/phpunit/includes/search/SearchUpdateTest.php b/tests/phpunit/includes/search/SearchUpdateTest.php deleted file mode 100644 index 6e49a9a1..00000000 --- a/tests/phpunit/includes/search/SearchUpdateTest.php +++ /dev/null @@ -1,90 +0,0 @@ -doUpdate(); - return array( MockSearch::$title, MockSearch::$text ); - } - - function updateText( $text ) { - list( , $resultText ) = $this->update( $text ); - $resultText = trim( $resultText ); // abstract from some implementation details - return $resultText; - } - - function setUp() { - global $wgSearchType; - - self::$searchType = $wgSearchType; - $wgSearchType = 'MockSearch'; - } - - function tearDown() { - global $wgSearchType; - - $wgSearchType = self::$searchType; - } - - function testUpdateText() { - $this->assertEquals( - 'test', - $this->updateText( '
TeSt
' ), - 'HTML stripped, text lowercased' - ); - - $this->assertEquals( - 'foo bar boz quux', - $this->updateText( << -
foo
bar - bozquux - -EOT - ), 'Stripping HTML tables' ); - - $this->assertEquals( - 'a b', - $this->updateText( 'a > b' ), - 'Handle unclosed tags' - ); - - $text = str_pad( "foo assertNotEquals( - '', - $this->updateText( $text ), - 'Bug 18609' - ); - } - - function testBug32712() { - $text = "text „http://example.com“ text"; - $result = $this->updateText( $text ); - $processed = preg_replace( '/Q/u', 'Q', $result ); - $this->assertTrue( - $processed != '', - 'Link surrounded by unicode quotes should not fail UTF-8 validation' - ); - } -} diff --git a/tests/phpunit/includes/specials/QueryAllSpecialPagesTest.php b/tests/phpunit/includes/specials/QueryAllSpecialPagesTest.php deleted file mode 100644 index a33c7b68..00000000 --- a/tests/phpunit/includes/specials/QueryAllSpecialPagesTest.php +++ /dev/null @@ -1,79 +0,0 @@ -manualTest ) ) { - $this->queryPages[$class] = new $class; - } - } - } - - /** - * Test SQL for each of our QueryPages objects - * @group Database - */ - function testQuerypageSqlQuery() { - global $wgDBtype; - - foreach( $this->queryPages as $page ) { - - // With MySQL, skips special pages reopening a temporary table - // See http://bugs.mysql.com/bug.php?id=10327 - if( - $wgDBtype === 'mysql' - && in_array( $page->getName(), $this->reopensTempTable ) - ) { - $this->markTestSkipped( "SQL query for page {$page->getName()} can not be tested on MySQL backend (it reopens a temporary table)" ); - continue; - } - - $msg = "SQL query for page {$page->getName()} should give a result wrapper object" ; - - $result = $page->reallyDoQuery( 50 ); - if( $result instanceof ResultWrapper ) { - $this->assertTrue( true, $msg ); - } else { - $this->assertFalse( false, $msg ); - } - } - } -} diff --git a/tests/phpunit/includes/specials/SpecialRecentchangesTest.php b/tests/phpunit/includes/specials/SpecialRecentchangesTest.php deleted file mode 100644 index 2e4f4b09..00000000 --- a/tests/phpunit/includes/specials/SpecialRecentchangesTest.php +++ /dev/null @@ -1,132 +0,0 @@ -setRequest( new FauxRequest( $requestOptions ) ); - - # setup the rc object - $this->rc = new SpecialRecentChanges(); - $this->rc->setContext( $context ); - $formOptions = $this->rc->setup( null ); - - # Filter out rc_timestamp conditions which depends on the test runtime - # This condition is not needed as of march 2, 2011 -- hashar - # @todo FIXME: Find a way to generate the correct rc_timestamp - $queryConditions = array_filter( - $this->rc->buildMainQueryConds( $formOptions ), - 'SpecialRecentchangesTest::filterOutRcTimestampCondition' - ); - - $this->assertEquals( - $expected, - $queryConditions, - $message - ); - } - - /** return false if condition begin with 'rc_timestamp ' */ - private static function filterOutRcTimestampCondition( $var ) { - return (false === strpos( $var, 'rc_timestamp ' )); - - } - - public function testRcNsFilter() { - $this->assertConditions( - array( # expected - 'rc_bot' => 0, - #0 => "rc_timestamp >= '20110223000000'", - 1 => "rc_namespace = '0'", - ), - array( - 'namespace' => NS_MAIN, - ), - "rc conditions with no options (aka default setting)" - ); - } - - public function testRcNsFilterInversion() { - $this->assertConditions( - array( # expected - #0 => "rc_timestamp >= '20110223000000'", - 'rc_bot' => 0, - 1 => sprintf( "rc_namespace != '%s'", NS_MAIN ), - ), - array( - 'namespace' => NS_MAIN, - 'invert' => 1, - ), - "rc conditions with namespace inverted" - ); - } - - /** - * @bug 2429 - * @dataProvider provideNamespacesAssociations - */ - public function testRcNsFilterAssociation( $ns1, $ns2 ) { - $this->assertConditions( - array( # expected - #0 => "rc_timestamp >= '20110223000000'", - 'rc_bot' => 0, - 1 => sprintf( "(rc_namespace = '%s' OR rc_namespace = '%s')", $ns1, $ns2 ), - ), - array( - 'namespace' => $ns1, - 'associated' => 1, - ), - "rc conditions with namespace inverted" - ); - } - - /** - * @bug 2429 - * @dataProvider provideNamespacesAssociations - */ - public function testRcNsFilterAssociationWithInversion( $ns1, $ns2 ) { - $this->assertConditions( - array( # expected - #0 => "rc_timestamp >= '20110223000000'", - 'rc_bot' => 0, - 1 => sprintf( "(rc_namespace != '%s' AND rc_namespace != '%s')", $ns1, $ns2 ), - ), - array( - 'namespace' => $ns1, - 'associated' => 1, - 'invert' => 1, - ), - "rc conditions with namespace inverted" - ); - } - - /** - * Provides associated namespaces to test recent changes - * namespaces association filtering. - */ - public function provideNamespacesAssociations() { - return array( # (NS => Associated_NS) - array( NS_MAIN, NS_TALK), - array( NS_TALK, NS_MAIN), - ); - } - -} - - diff --git a/tests/phpunit/includes/specials/SpecialSearchTest.php b/tests/phpunit/includes/specials/SpecialSearchTest.php deleted file mode 100644 index 20e42a68..00000000 --- a/tests/phpunit/includes/specials/SpecialSearchTest.php +++ /dev/null @@ -1,116 +0,0 @@ - true, 'ns6' => true). NULL to use default options. - * @param $userOptions Array User options to test with. For example array('searchNs5' => 1 );. NULL to use default options. - * @param $expectedProfile An expected search profile name - * @param $expectedNs Array Expected namespaces - */ - function testProfileAndNamespaceLoading( - $requested, $userOptions, $expectedProfile, $expectedNS, - $message = 'Profile name and namespaces mismatches!' - ) { - $context = new RequestContext; - $context->setUser( - $this->newUserWithSearchNS( $userOptions ) - ); - /* - $context->setRequest( new FauxRequest( array( - 'ns5'=>true, - 'ns6'=>true, - ) )); - */ - $context->setRequest( new FauxRequest( $requested )); - $search = new SpecialSearch(); - $search->setContext( $context ); - $search->load(); - - /** - * Verify profile name and namespace in the same assertion to make - * sure we will be able to fully compare the above code. PHPUnit stop - * after an assertion fail. - */ - $this->assertEquals( - array( /** Expected: */ - 'ProfileName' => $expectedProfile, - 'Namespaces' => $expectedNS, - ) - , array( /** Actual: */ - 'ProfileName' => $search->getProfile(), - 'Namespaces' => $search->getNamespaces(), - ) - , $message - ); - - } - - function provideSearchOptionsTests() { - $defaultNS = SearchEngine::defaultNamespaces(); - $EMPTY_REQUEST = array(); - $NO_USER_PREF = null; - - return array( - /** - * Parameters: - * , - * Followed by expected values: - * , - * Then an optional message. - */ - array( - $EMPTY_REQUEST, $NO_USER_PREF, - 'default', $defaultNS, - 'Bug 33270: No request nor user preferences should give default profile' - ), - array( - array( 'ns5' => 1 ), $NO_USER_PREF, - 'advanced', array( 5), - 'Web request with specific NS should override user preference' - ), - array( - $EMPTY_REQUEST, array( 'searchNs2' => 1, 'searchNs14' => 1 ), - 'advanced', array( 2, 14 ), - 'Bug 33583: search with no option should honor User search preferences' - ), - array( - $EMPTY_REQUEST, array_fill_keys( array_map( function( $ns ) { - return "searchNs$ns"; - }, $defaultNS ), 0 ) + array( 'searchNs2' => 1, 'searchNs14' => 1 ), - 'advanced', array( 2, 14 ), - 'Bug 33583: search with no option should honor User search preferences' - . 'and have all other namespace disabled' - ), - ); - } - - /** - * Helper to create a new User object with given options - * User remains anonymous though - */ - function newUserWithSearchNS( $opt = null ) { - $u = User::newFromId(0); - if( $opt === null ) { - return $u; - } - foreach($opt as $name => $value) { - $u->setOption( $name, $value ); - } - return $u; - } -} - diff --git a/tests/phpunit/includes/upload/UploadFromUrlTest.php b/tests/phpunit/includes/upload/UploadFromUrlTest.php deleted file mode 100644 index f66c387b..00000000 --- a/tests/phpunit/includes/upload/UploadFromUrlTest.php +++ /dev/null @@ -1,351 +0,0 @@ -exists() ) { - $this->deleteFile( 'UploadFromUrlTest.png' ); - } - } - - protected function doApiRequest( Array $params, Array $unused = null, $appendModule = false, User $user = null ) { - $sessionId = session_id(); - session_write_close(); - - $req = new FauxRequest( $params, true, $_SESSION ); - $module = new ApiMain( $req, true ); - $module->execute(); - - wfSetupSession( $sessionId ); - return array( $module->getResultData(), $req ); - } - - /** - * Ensure that the job queue is empty before continuing - */ - public function testClearQueue() { - $job = Job::pop(); - while ( $job ) { - $job = Job::pop(); - } - $this->assertFalse( $job ); - } - - /** - * @todo Document why we test login, since the $wgUser hack used doesn't - * require login - */ - public function testLogin() { - $data = $this->doApiRequest( array( - 'action' => 'login', - 'lgname' => $this->user->userName, - 'lgpassword' => $this->user->passWord ) ); - $this->assertArrayHasKey( "login", $data[0] ); - $this->assertArrayHasKey( "result", $data[0]['login'] ); - $this->assertEquals( "NeedToken", $data[0]['login']['result'] ); - $token = $data[0]['login']['token']; - - $data = $this->doApiRequest( array( - 'action' => 'login', - "lgtoken" => $token, - 'lgname' => $this->user->userName, - 'lgpassword' => $this->user->passWord ) ); - - $this->assertArrayHasKey( "login", $data[0] ); - $this->assertArrayHasKey( "result", $data[0]['login'] ); - $this->assertEquals( "Success", $data[0]['login']['result'] ); - $this->assertArrayHasKey( 'lgtoken', $data[0]['login'] ); - - return $data; - } - - /** - * @depends testLogin - * @depends testClearQueue - */ - public function testSetupUrlDownload( $data ) { - $token = $this->user->getEditToken(); - $exception = false; - - try { - $this->doApiRequest( array( - 'action' => 'upload', - ) ); - } catch ( UsageException $e ) { - $exception = true; - $this->assertEquals( "The token parameter must be set", $e->getMessage() ); - } - $this->assertTrue( $exception, "Got exception" ); - - $exception = false; - try { - $this->doApiRequest( array( - 'action' => 'upload', - 'token' => $token, - ), $data ); - } catch ( UsageException $e ) { - $exception = true; - $this->assertEquals( "One of the parameters sessionkey, file, url, statuskey is required", - $e->getMessage() ); - } - $this->assertTrue( $exception, "Got exception" ); - - $exception = false; - try { - $this->doApiRequest( array( - 'action' => 'upload', - 'url' => 'http://www.example.com/test.png', - 'token' => $token, - ), $data ); - } catch ( UsageException $e ) { - $exception = true; - $this->assertEquals( "The filename parameter must be set", $e->getMessage() ); - } - $this->assertTrue( $exception, "Got exception" ); - - $this->user->removeGroup( 'sysop' ); - $exception = false; - try { - $this->doApiRequest( array( - 'action' => 'upload', - 'url' => 'http://www.example.com/test.png', - 'filename' => 'UploadFromUrlTest.png', - 'token' => $token, - ), $data ); - } catch ( UsageException $e ) { - $exception = true; - $this->assertEquals( "Permission denied", $e->getMessage() ); - } - $this->assertTrue( $exception, "Got exception" ); - - $this->user->addGroup( 'sysop' ); - $data = $this->doApiRequest( array( - 'action' => 'upload', - 'url' => 'http://bits.wikimedia.org/skins-1.5/common/images/poweredby_mediawiki_88x31.png', - 'asyncdownload' => 1, - 'filename' => 'UploadFromUrlTest.png', - 'token' => $token, - ), $data ); - - $this->assertEquals( $data[0]['upload']['result'], 'Queued', 'Queued upload' ); - - $job = Job::pop(); - $this->assertThat( $job, $this->isInstanceOf( 'UploadFromUrlJob' ), 'Queued upload inserted' ); - } - - /** - * @depends testLogin - * @depends testClearQueue - */ - public function testAsyncUpload( $data ) { - $token = $this->user->getEditToken(); - - $this->user->addGroup( 'users' ); - - $data = $this->doAsyncUpload( $token, true ); - $this->assertEquals( $data[0]['upload']['result'], 'Success' ); - $this->assertEquals( $data[0]['upload']['filename'], 'UploadFromUrlTest.png' ); - $this->assertTrue( wfLocalFile( $data[0]['upload']['filename'] )->exists() ); - - $this->deleteFile( 'UploadFromUrlTest.png' ); - - return $data; - } - - /** - * @depends testLogin - * @depends testClearQueue - */ - public function testAsyncUploadWarning( $data ) { - $token = $this->user->getEditToken(); - - $this->user->addGroup( 'users' ); - - - $data = $this->doAsyncUpload( $token ); - - $this->assertEquals( $data[0]['upload']['result'], 'Warning' ); - $this->assertTrue( isset( $data[0]['upload']['sessionkey'] ) ); - - $data = $this->doApiRequest( array( - 'action' => 'upload', - 'sessionkey' => $data[0]['upload']['sessionkey'], - 'filename' => 'UploadFromUrlTest.png', - 'ignorewarnings' => 1, - 'token' => $token, - ) ); - $this->assertEquals( $data[0]['upload']['result'], 'Success' ); - $this->assertEquals( $data[0]['upload']['filename'], 'UploadFromUrlTest.png' ); - $this->assertTrue( wfLocalFile( $data[0]['upload']['filename'] )->exists() ); - - $this->deleteFile( 'UploadFromUrlTest.png' ); - - return $data; - } - - /** - * @depends testLogin - * @depends testClearQueue - */ - public function testSyncDownload( $data ) { - $token = $this->user->getEditToken(); - - $job = Job::pop(); - $this->assertFalse( $job, 'Starting with an empty jobqueue' ); - - $this->user->addGroup( 'users' ); - $data = $this->doApiRequest( array( - 'action' => 'upload', - 'filename' => 'UploadFromUrlTest.png', - 'url' => 'http://bits.wikimedia.org/skins-1.5/common/images/poweredby_mediawiki_88x31.png', - 'ignorewarnings' => true, - 'token' => $token, - ), $data ); - - $job = Job::pop(); - $this->assertFalse( $job ); - - $this->assertEquals( 'Success', $data[0]['upload']['result'] ); - $this->deleteFile( 'UploadFromUrlTest.png' ); - - return $data; - } - - public function testLeaveMessage() { - $token = $this->user->user->getEditToken(); - - $talk = $this->user->user->getTalkPage(); - if ( $talk->exists() ) { - $page = WikiPage::factory( $talk ); - $page->doDeleteArticle( '' ); - } - - $this->assertFalse( (bool)$talk->getArticleID( Title::GAID_FOR_UPDATE ), 'User talk does not exist' ); - - $data = $this->doApiRequest( array( - 'action' => 'upload', - 'filename' => 'UploadFromUrlTest.png', - 'url' => 'http://bits.wikimedia.org/skins-1.5/common/images/poweredby_mediawiki_88x31.png', - 'asyncdownload' => 1, - 'token' => $token, - 'leavemessage' => 1, - 'ignorewarnings' => 1, - ) ); - - $job = Job::pop(); - $this->assertEquals( 'UploadFromUrlJob', get_class( $job ) ); - $job->run(); - - $this->assertTrue( wfLocalFile( 'UploadFromUrlTest.png' )->exists() ); - $this->assertTrue( (bool)$talk->getArticleID( Title::GAID_FOR_UPDATE ), 'User talk exists' ); - - $this->deleteFile( 'UploadFromUrlTest.png' ); - - $talkRev = Revision::newFromTitle( $talk ); - $talkSize = $talkRev->getSize(); - - $exception = false; - try { - $data = $this->doApiRequest( array( - 'action' => 'upload', - 'filename' => 'UploadFromUrlTest.png', - 'url' => 'http://bits.wikimedia.org/skins-1.5/common/images/poweredby_mediawiki_88x31.png', - 'asyncdownload' => 1, - 'token' => $token, - 'leavemessage' => 1, - ) ); - } catch ( UsageException $e ) { - $exception = true; - $this->assertEquals( 'Using leavemessage without ignorewarnings is not supported', $e->getMessage() ); - } - $this->assertTrue( $exception ); - - $job = Job::pop(); - $this->assertFalse( $job ); - - return; - - /* - // Broken until using leavemessage with ignorewarnings is supported - $job->run(); - - $this->assertFalse( wfLocalFile( 'UploadFromUrlTest.png' )->exists() ); - - $talkRev = Revision::newFromTitle( $talk ); - $this->assertTrue( $talkRev->getSize() > $talkSize, 'New message left' ); - */ - } - - /** - * Helper function to perform an async upload, execute the job and fetch - * the status - * - * @return array The result of action=upload&statuskey=key - */ - private function doAsyncUpload( $token, $ignoreWarnings = false, $leaveMessage = false ) { - $params = array( - 'action' => 'upload', - 'filename' => 'UploadFromUrlTest.png', - 'url' => 'http://bits.wikimedia.org/skins-1.5/common/images/poweredby_mediawiki_88x31.png', - 'asyncdownload' => 1, - 'token' => $token, - ); - if ( $ignoreWarnings ) { - $params['ignorewarnings'] = 1; - } - if ( $leaveMessage ) { - $params['leavemessage'] = 1; - } - - $data = $this->doApiRequest( $params ); - $this->assertEquals( $data[0]['upload']['result'], 'Queued' ); - $this->assertTrue( isset( $data[0]['upload']['statuskey'] ) ); - $statusKey = $data[0]['upload']['statuskey']; - - $job = Job::pop(); - $this->assertEquals( 'UploadFromUrlJob', get_class( $job ) ); - - $status = $job->run(); - $this->assertTrue( $status ); - - $data = $this->doApiRequest( array( - 'action' => 'upload', - 'statuskey' => $statusKey, - 'token' => $token, - ) ); - - return $data; - } - - - /** - * - */ - protected function deleteFile( $name ) { - $t = Title::newFromText( $name, NS_FILE ); - $this->assertTrue($t->exists(), "File '$name' exists"); - - if ( $t->exists() ) { - $file = wfFindFile( $name, array( 'ignoreRedirect' => true ) ); - $empty = ""; - FileDeleteForm::doDelete( $t, $file, $empty, "none", true ); - $page = WikiPage::factory( $t ); - $page->doDeleteArticle( "testing" ); - } - $t = Title::newFromText( $name, NS_FILE ); - - $this->assertFalse($t->exists(), "File '$name' was deleted"); - } - } diff --git a/tests/phpunit/includes/upload/UploadStashTest.php b/tests/phpunit/includes/upload/UploadStashTest.php deleted file mode 100644 index 66fafaaf..00000000 --- a/tests/phpunit/includes/upload/UploadStashTest.php +++ /dev/null @@ -1,77 +0,0 @@ -bug29408File = __DIR__ . '/bug29408'; - file_put_contents( $this->bug29408File, "\x00" ); - - self::$users = array( - 'sysop' => new TestUser( - 'Uploadstashtestsysop', - 'Upload Stash Test Sysop', - 'upload_stash_test_sysop@example.com', - array( 'sysop' ) - ), - 'uploader' => new TestUser( - 'Uploadstashtestuser', - 'Upload Stash Test User', - 'upload_stash_test_user@example.com', - array() - ) - ); - } - - public function testBug29408() { - global $wgUser; - $wgUser = self::$users['uploader']->user; - - $repo = RepoGroup::singleton()->getLocalRepo(); - $stash = new UploadStash( $repo ); - - // Throws exception caught by PHPUnit on failure - $file = $stash->stashFile( $this->bug29408File ); - // We'll never reach this point if we hit bug 29408 - $this->assertTrue( true, 'Unrecognized file without extension' ); - - $stash->removeFile( $file->getFileKey() ); - } - - public function testValidRequest() { - $request = new FauxRequest( array( 'wpFileKey' => 'foo') ); - $this->assertFalse( UploadFromStash::isValidRequest($request), 'Check failure on bad wpFileKey' ); - - $request = new FauxRequest( array( 'wpSessionKey' => 'foo') ); - $this->assertFalse( UploadFromStash::isValidRequest($request), 'Check failure on bad wpSessionKey' ); - - $request = new FauxRequest( array( 'wpFileKey' => 'testkey-test.test') ); - $this->assertTrue( UploadFromStash::isValidRequest($request), 'Check good wpFileKey' ); - - $request = new FauxRequest( array( 'wpFileKey' => 'testkey-test.test') ); - $this->assertTrue( UploadFromStash::isValidRequest($request), 'Check good wpSessionKey' ); - - $request = new FauxRequest( array( 'wpFileKey' => 'testkey-test.test', 'wpSessionKey' => 'foo') ); - $this->assertTrue( UploadFromStash::isValidRequest($request), 'Check key precedence' ); - } - - public function tearDown() { - parent::tearDown(); - - if( file_exists( $this->bug29408File . "." ) ) { - unlink( $this->bug29408File . "." ); - } - - if( file_exists( $this->bug29408File ) ) { - unlink( $this->bug29408File ); - } - } -} diff --git a/tests/phpunit/includes/upload/UploadTest.php b/tests/phpunit/includes/upload/UploadTest.php deleted file mode 100644 index 6948f5b1..00000000 --- a/tests/phpunit/includes/upload/UploadTest.php +++ /dev/null @@ -1,141 +0,0 @@ -upload = new UploadTestHandler; - $this->hooks = $wgHooks; - $wgHooks['InterwikiLoadPrefix'][] = function( $prefix, &$data ) { - return false; - }; - } - - function tearDown() { - global $wgHooks; - $wgHooks = $this->hooks; - } - - - /** - * First checks the return code - * of UploadBase::getTitle() and then the actual returned title - * - * @dataProvider dataTestTitleValidation - */ - public function testTitleValidation( $srcFilename, $dstFilename, $code, $msg ) { - /* Check the result code */ - $this->assertEquals( $code, - $this->upload->testTitleValidation( $srcFilename ), - "$msg code" ); - - /* If we expect a valid title, check the title itself. */ - if ( $code == UploadBase::OK ) { - $this->assertEquals( $dstFilename, - $this->upload->getTitle()->getText(), - "$msg text" ); - } - } - - /** - * Test various forms of valid and invalid titles that can be supplied. - */ - public function dataTestTitleValidation() { - return array( - /* Test a valid title */ - array( 'ValidTitle.jpg', 'ValidTitle.jpg', UploadBase::OK, - 'upload valid title' ), - /* A title with a slash */ - array( 'A/B.jpg', 'B.jpg', UploadBase::OK, - 'upload title with slash' ), - /* A title with illegal char */ - array( 'A:B.jpg', 'A-B.jpg', UploadBase::OK, - 'upload title with colon' ), - /* Stripping leading File: prefix */ - array( 'File:C.jpg', 'C.jpg', UploadBase::OK, - 'upload title with File prefix' ), - /* Test illegal suggested title (r94601) */ - array( '%281%29.JPG', null, UploadBase::ILLEGAL_FILENAME, - 'illegal title for upload' ), - /* A title without extension */ - array( 'A', null, UploadBase::FILETYPE_MISSING, - 'upload title without extension' ), - /* A title with no basename */ - array( '.jpg', null, UploadBase::MIN_LENGTH_PARTNAME, - 'upload title without basename' ), - /* A title that is longer than 255 bytes */ - array( str_repeat( 'a', 255 ) . '.jpg', null, UploadBase::FILENAME_TOO_LONG, - 'upload title longer than 255 bytes' ), - /* A title that is longer than 240 bytes */ - array( str_repeat( 'a', 240 ) . '.jpg', null, UploadBase::FILENAME_TOO_LONG, - 'upload title longer than 240 bytes' ), - ); - } - - /** - * Test the upload verification functions - */ - public function testVerifyUpload() { - /* Setup with zero file size */ - $this->upload->initializePathInfo( '', '', 0 ); - $result = $this->upload->verifyUpload(); - $this->assertEquals( UploadBase::EMPTY_FILE, - $result['status'], - 'upload empty file' ); - } - - // Helper used to create an empty file of size $size. - private function createFileOfSize( $size ) { - $filename = tempnam( wfTempDir(), "mwuploadtest" ); - - $fh = fopen( $filename, 'w' ); - ftruncate( $fh, $size ); - fclose( $fh ); - - return $filename; - } - - /** - * test uploading a 100 bytes file with $wgMaxUploadSize = 100 - * - * This method should be abstracted so we can test different settings. - */ - - public function testMaxUploadSize() { - global $wgMaxUploadSize; - $savedGlobal = $wgMaxUploadSize; // save global - global $wgFileExtensions; - $wgFileExtensions[] = 'txt'; - - $wgMaxUploadSize = 100; - - $filename = $this->createFileOfSize( $wgMaxUploadSize ); - $this->upload->initializePathInfo( basename($filename) . '.txt', $filename, 100 ); - $result = $this->upload->verifyUpload(); - unlink( $filename ); - - $this->assertEquals( - array( 'status' => UploadBase::OK ), $result ); - - $wgMaxUploadSize = $savedGlobal; // restore global - } -} - -class UploadTestHandler extends UploadBase { - public function initializeFromRequest( &$request ) { } - public function testTitleValidation( $name ) { - $this->mTitle = false; - $this->mDesiredDestName = $name; - $this->mTitleError = UploadBase::OK; - $this->getTitle(); - return $this->mTitleError; - } - - -} -- cgit v1.2.2