MediaWiki  1.32.5
MessageCacheTest.php
Go to the documentation of this file.
1 <?php
2 
4 
11 
12  protected function setUp() {
13  parent::setUp();
14  $this->configureLanguages();
16  MessageCache::singleton()->enable();
17  }
18 
22  protected function configureLanguages() {
23  // for the test, we need the content language to be anything but English,
24  // let's choose e.g. German (de)
25  $this->setUserLang( 'de' );
26  $this->setContentLang( 'de' );
27  }
28 
29  function addDBDataOnce() {
30  $this->configureLanguages();
31 
32  // Set up messages and fallbacks ab -> ru -> de
33  $this->makePage( 'FallbackLanguageTest-Full', 'ab' );
34  $this->makePage( 'FallbackLanguageTest-Full', 'ru' );
35  $this->makePage( 'FallbackLanguageTest-Full', 'de' );
36 
37  // Fallbacks where ab does not exist
38  $this->makePage( 'FallbackLanguageTest-Partial', 'ru' );
39  $this->makePage( 'FallbackLanguageTest-Partial', 'de' );
40 
41  // Fallback to the content language
42  $this->makePage( 'FallbackLanguageTest-ContLang', 'de' );
43 
44  // Add customizations for an existing message.
45  $this->makePage( 'sunday', 'ru' );
46 
47  // Full key tests -- always want russian
48  $this->makePage( 'MessageCacheTest-FullKeyTest', 'ab' );
49  $this->makePage( 'MessageCacheTest-FullKeyTest', 'ru' );
50 
51  // In content language -- get base if no derivative
52  $this->makePage( 'FallbackLanguageTest-NoDervContLang', 'de', 'de/none' );
53  }
54 
62  protected function makePage( $title, $lang, $content = null ) {
63  if ( $content === null ) {
64  $content = $lang;
65  }
66  if ( $lang !== MediaWikiServices::getInstance()->getContentLanguage()->getCode() ) {
67  $title = "$title/$lang";
68  }
69 
71  $wikiPage = new WikiPage( $title );
72  $contentHandler = ContentHandler::makeContent( $content, $title );
73  $wikiPage->doEditContent( $contentHandler, "$lang translation test case" );
74  }
75 
81  public function testMessageFallbacks( $message, $lang, $expectedContent ) {
82  $result = MessageCache::singleton()->get( $message, true, $lang );
83  $this->assertEquals( $expectedContent, $result, "Message fallback failed." );
84  }
85 
87  return [
88  [ 'FallbackLanguageTest-Full', 'ab', 'ab' ],
89  [ 'FallbackLanguageTest-Partial', 'ab', 'ru' ],
90  [ 'FallbackLanguageTest-ContLang', 'ab', 'de' ],
91  [ 'FallbackLanguageTest-None', 'ab', false ],
92 
93  // Existing message with customizations on the fallbacks
94  [ 'sunday', 'ab', 'амҽыш' ],
95 
96  // T48579
97  [ 'FallbackLanguageTest-NoDervContLang', 'de', 'de/none' ],
98  // UI language different from content language should only use de/none as last option
99  [ 'FallbackLanguageTest-NoDervContLang', 'fit', 'de/none' ],
100  ];
101  }
102 
103  public function testReplaceMsg() {
104  $messageCache = MessageCache::singleton();
105  $message = 'go';
106  $uckey = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst( $message );
107  $oldText = $messageCache->get( $message ); // "Ausführen"
108 
109  $dbw = wfGetDB( DB_MASTER );
110  $dbw->startAtomic( __METHOD__ ); // simulate request and block deferred updates
111  $messageCache->replace( $uckey, 'Allez!' );
112  $this->assertEquals( 'Allez!',
113  $messageCache->getMsgFromNamespace( $uckey, 'de' ),
114  'Updates are reflected in-process immediately' );
115  $this->assertEquals( 'Allez!',
116  $messageCache->get( $message ),
117  'Updates are reflected in-process immediately' );
118  $this->makePage( 'Go', 'de', 'Race!' );
119  $dbw->endAtomic( __METHOD__ );
120 
121  $this->assertEquals( 0,
123  'Post-commit deferred update triggers a run of all updates' );
124 
125  $this->assertEquals( 'Race!', $messageCache->get( $message ), 'Correct final contents' );
126 
127  $this->makePage( 'Go', 'de', $oldText );
128  $messageCache->replace( $uckey, $oldText ); // deferred update runs immediately
129  $this->assertEquals( $oldText, $messageCache->get( $message ), 'Content restored' );
130  }
131 
132  public function testReplaceCache() {
133  global $wgWANObjectCaches;
134 
135  // We need a WAN cache for this.
136  $this->setMwGlobals( [
137  'wgMainWANCache' => 'hash',
138  'wgWANObjectCaches' => $wgWANObjectCaches + [
139  'hash' => [
140  'class' => WANObjectCache::class,
141  'cacheId' => 'hash',
142  'channels' => []
143  ]
144  ]
145  ] );
146  $this->overrideMwServices();
147 
149  $messageCache = MessageCache::singleton();
150  $messageCache->enable();
151 
152  // Populate one key
153  $this->makePage( 'Key1', 'de', 'Value1' );
154  $this->assertEquals( 0,
156  'Post-commit deferred update triggers a run of all updates' );
157  $this->assertEquals( 'Value1', $messageCache->get( 'Key1' ), 'Key1 was successfully edited' );
158 
159  // Screw up the database so MessageCache::loadFromDB() will
160  // produce the wrong result for reloading Key1
161  $this->db->delete(
162  'page', [ 'page_namespace' => NS_MEDIAWIKI, 'page_title' => 'Key1' ], __METHOD__
163  );
164 
165  // Populate the second key
166  $this->makePage( 'Key2', 'de', 'Value2' );
167  $this->assertEquals( 0,
169  'Post-commit deferred update triggers a run of all updates' );
170  $this->assertEquals( 'Value2', $messageCache->get( 'Key2' ), 'Key2 was successfully edited' );
171 
172  // Now test that the second edit didn't reload Key1
173  $this->assertEquals( 'Value1', $messageCache->get( 'Key1' ),
174  'Key1 wasn\'t reloaded by edit of Key2' );
175  }
176 
180  public function testNormalizeKey( $key, $expected ) {
181  $actual = MessageCache::normalizeKey( $key );
182  $this->assertEquals( $expected, $actual );
183  }
184 
185  public function provideNormalizeKey() {
186  return [
187  [ 'Foo', 'foo' ],
188  [ 'foo', 'foo' ],
189  [ 'fOo', 'fOo' ],
190  [ 'FOO', 'fOO' ],
191  [ 'Foo bar', 'foo_bar' ],
192  [ 'Ćab', 'ćab' ],
193  [ 'Ćab_e 3', 'ćab_e_3' ],
194  [ 'ĆAB', 'ćAB' ],
195  [ 'ćab', 'ćab' ],
196  [ 'ćaB', 'ćaB' ],
197  ];
198  }
199 
200  public function testNoDBAccess() {
201  global $wgContLanguageCode;
202 
203  $dbr = wfGetDB( DB_REPLICA );
204 
205  MessageCache::singleton()->getMsgFromNamespace( 'allpages', $wgContLanguageCode );
206 
207  $this->assertEquals( 0, $dbr->trxLevel() );
208  $dbr->setFlag( DBO_TRX, $dbr::REMEMBER_PRIOR ); // make queries trigger TRX
209 
210  MessageCache::singleton()->getMsgFromNamespace( 'go', $wgContLanguageCode );
211 
212  $dbr->restoreFlags();
213 
214  $this->assertEquals( 0, $dbr->trxLevel(), "No DB read queries" );
215  }
216 }
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:280
MessageCacheTest
Database Cache MessageCache.
Definition: MessageCacheTest.php:10
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
MessageCache\normalizeKey
static normalizeKey( $key)
Normalize message key input.
Definition: MessageCache.php:154
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:33
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:2042
$wgWANObjectCaches
$wgWANObjectCaches
Advanced WAN object cache configuration.
Definition: DefaultSettings.php:2446
WikiPage
Class representing a MediaWiki article and history.
Definition: WikiPage.php:44
MessageCacheTest\testNoDBAccess
testNoDBAccess()
Definition: MessageCacheTest.php:200
DBO_TRX
const DBO_TRX
Definition: defines.php:12
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
$dbr
$dbr
Definition: testCompression.php:50
MediaWikiTestCase\overrideMwServices
overrideMwServices(Config $configOverrides=null, array $services=[])
Stashes the global instance of MediaWikiServices, and installs a new one, allowing test cases to over...
Definition: MediaWikiTestCase.php:934
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:964
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2693
MediaWikiTestCase\setMwGlobals
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.
Definition: MediaWikiTestCase.php:706
MessageCacheTest\testReplaceCache
testReplaceCache()
Definition: MessageCacheTest.php:132
MessageCacheTest\configureLanguages
configureLanguages()
Helper function – setup site language for testing.
Definition: MessageCacheTest.php:22
MessageCacheTest\provideMessagesForFallback
provideMessagesForFallback()
Definition: MessageCacheTest.php:86
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
MediaWikiTestCase\setUserLang
setUserLang( $lang)
Definition: MediaWikiTestCase.php:1054
DB_MASTER
const DB_MASTER
Definition: defines.php:26
MessageCacheTest\addDBDataOnce
addDBDataOnce()
Stub.
Definition: MessageCacheTest.php:29
MessageCache\singleton
static singleton()
Get the signleton instance of this class.
Definition: MessageCache.php:120
ContentHandler\makeContent
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
Definition: ContentHandler.php:133
MessageCacheTest\testMessageFallbacks
testMessageFallbacks( $message, $lang, $expectedContent)
Test message fallbacks, T3495.
Definition: MessageCacheTest.php:81
MediaWikiTestCase\setContentLang
setContentLang( $lang)
Definition: MediaWikiTestCase.php:1063
MessageCacheTest\makePage
makePage( $title, $lang, $content=null)
Helper function for addDBData – adds a simple page to the database.
Definition: MessageCacheTest.php:62
MessageCacheTest\testNormalizeKey
testNormalizeKey( $key, $expected)
provideNormalizeKey
Definition: MessageCacheTest.php:180
MessageCacheTest\setUp
setUp()
Definition: MessageCacheTest.php:12
MediaWikiLangTestCase
Base class that store and restore the Language objects.
Definition: MediaWikiLangTestCase.php:8
MessageCacheTest\testReplaceMsg
testReplaceMsg()
Definition: MessageCacheTest.php:103
DeferredUpdates\pendingUpdatesCount
static pendingUpdatesCount()
Definition: DeferredUpdates.php:348
MessageCacheTest\provideNormalizeKey
provideNormalizeKey()
Definition: MessageCacheTest.php:185
$wgContLanguageCode
foreach(LanguageCode::getNonstandardLanguageCodeMapping() as $code=> $bcp47) $wgContLanguageCode
Definition: Setup.php:522
$content
$content
Definition: pageupdater.txt:72
NS_MEDIAWIKI
const NS_MEDIAWIKI
Definition: Defines.php:72
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
MediaWikiServices
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
MessageCache\destroyInstance
static destroyInstance()
Destroy the singleton instance.
Definition: MessageCache.php:144