MediaWiki  REL1_31
NameTableStoreTest.php
Go to the documentation of this file.
1 <?php
2 
4 
11 use Psr\Log\NullLogger;
15 use Wikimedia\TestingAccessWrapper;
16 
23 
24  public function setUp() {
25  $this->tablesUsed[] = 'slot_roles';
26  parent::setUp();
27  }
28 
29  private function populateTable( $values ) {
30  $insertValues = [];
31  foreach ( $values as $name ) {
32  $insertValues[] = [ 'role_name' => $name ];
33  }
34  $this->db->insert( 'slot_roles', $insertValues );
35  }
36 
37  private function getHashWANObjectCache( $cacheBag ) {
38  return new WANObjectCache( [ 'cache' => $cacheBag ] );
39  }
40 
45  private function getMockLoadBalancer( $db ) {
46  $mock = $this->getMockBuilder( LoadBalancer::class )
47  ->disableOriginalConstructor()
48  ->getMock();
49  $mock->expects( $this->any() )
50  ->method( 'getConnection' )
51  ->willReturn( $db );
52  return $mock;
53  }
54 
55  private function getCallCheckingDb( $insertCalls, $selectCalls ) {
56  $mock = $this->getMockBuilder( Database::class )
57  ->disableOriginalConstructor()
58  ->getMock();
59  $mock->expects( $this->exactly( $insertCalls ) )
60  ->method( 'insert' )
61  ->willReturnCallback( function () {
62  return call_user_func_array( [ $this->db, 'insert' ], func_get_args() );
63  } );
64  $mock->expects( $this->exactly( $selectCalls ) )
65  ->method( 'select' )
66  ->willReturnCallback( function () {
67  return call_user_func_array( [ $this->db, 'select' ], func_get_args() );
68  } );
69  $mock->expects( $this->exactly( $insertCalls ) )
70  ->method( 'affectedRows' )
71  ->willReturnCallback( function () {
72  return call_user_func_array( [ $this->db, 'affectedRows' ], func_get_args() );
73  } );
74  $mock->expects( $this->any() )
75  ->method( 'insertId' )
76  ->willReturnCallback( function () {
77  return call_user_func_array( [ $this->db, 'insertId' ], func_get_args() );
78  } );
79  return $mock;
80  }
81 
82  private function getNameTableSqlStore(
83  BagOStuff $cacheBag,
84  $insertCalls,
85  $selectCalls,
86  $normalizationCallback = null
87  ) {
88  return new NameTableStore(
89  $this->getMockLoadBalancer( $this->getCallCheckingDb( $insertCalls, $selectCalls ) ),
90  $this->getHashWANObjectCache( $cacheBag ),
91  new NullLogger(),
92  'slot_roles', 'role_id', 'role_name',
93  $normalizationCallback
94  );
95  }
96 
97  public function provideGetAndAcquireId() {
98  return [
99  'no wancache, empty table' =>
100  [ new EmptyBagOStuff(), true, 1, [], 'foo', 1 ],
101  'no wancache, one matching value' =>
102  [ new EmptyBagOStuff(), false, 1, [ 'foo' ], 'foo', 1 ],
103  'no wancache, one not matching value' =>
104  [ new EmptyBagOStuff(), true, 1, [ 'bar' ], 'foo', 2 ],
105  'no wancache, multiple, one matching value' =>
106  [ new EmptyBagOStuff(), false, 1, [ 'foo', 'bar' ], 'bar', 2 ],
107  'no wancache, multiple, no matching value' =>
108  [ new EmptyBagOStuff(), true, 1, [ 'foo', 'bar' ], 'baz', 3 ],
109  'wancache, empty table' =>
110  [ new HashBagOStuff(), true, 1, [], 'foo', 1 ],
111  'wancache, one matching value' =>
112  [ new HashBagOStuff(), false, 1, [ 'foo' ], 'foo', 1 ],
113  'wancache, one not matching value' =>
114  [ new HashBagOStuff(), true, 1, [ 'bar' ], 'foo', 2 ],
115  'wancache, multiple, one matching value' =>
116  [ new HashBagOStuff(), false, 1, [ 'foo', 'bar' ], 'bar', 2 ],
117  'wancache, multiple, no matching value' =>
118  [ new HashBagOStuff(), true, 1, [ 'foo', 'bar' ], 'baz', 3 ],
119  ];
120  }
121 
131  public function testGetAndAcquireId(
132  $cacheBag,
133  $needsInsert,
134  $selectCalls,
135  $existingValues,
136  $name,
137  $expectedId
138  ) {
139  $this->populateTable( $existingValues );
140  $store = $this->getNameTableSqlStore( $cacheBag, (int)$needsInsert, $selectCalls );
141 
142  // Some names will not initially exist
143  try {
144  $result = $store->getId( $name );
145  $this->assertSame( $expectedId, $result );
146  } catch ( NameTableAccessException $e ) {
147  if ( $needsInsert ) {
148  $this->assertTrue( true ); // Expected exception
149  } else {
150  $this->fail( 'Did not expect an exception, but got one: ' . $e->getMessage() );
151  }
152  }
153 
154  // All names should return their id here
155  $this->assertSame( $expectedId, $store->acquireId( $name ) );
156 
157  // acquireId inserted these names, so now everything should exist with getId
158  $this->assertSame( $expectedId, $store->getId( $name ) );
159 
160  // calling getId again will also still work, and not result in more selects
161  $this->assertSame( $expectedId, $store->getId( $name ) );
162  }
163 
165  yield [ 'A', 'a', 'strtolower' ];
166  yield [ 'b', 'B', 'strtoupper' ];
167  yield [
168  'X',
169  'X',
170  function ( $name ) {
171  return $name;
172  }
173  ];
174  yield [ 'ZZ', 'ZZ-a', __CLASS__ . '::appendDashAToString' ];
175  }
176 
177  public static function appendDashAToString( $string ) {
178  return $string . '-a';
179  }
180 
185  $nameIn,
186  $nameOut,
187  $normalizationCallback
188  ) {
189  $store = $this->getNameTableSqlStore(
190  new EmptyBagOStuff(),
191  1,
192  1,
193  $normalizationCallback
194  );
195  $acquiredId = $store->acquireId( $nameIn );
196  $this->assertSame( $nameOut, $store->getName( $acquiredId ) );
197  }
198 
199  public function provideGetName() {
200  return [
201  [ new HashBagOStuff(), 3, 3 ],
202  [ new EmptyBagOStuff(), 3, 3 ],
203  ];
204  }
205 
209  public function testGetName( $cacheBag, $insertCalls, $selectCalls ) {
210  $store = $this->getNameTableSqlStore( $cacheBag, $insertCalls, $selectCalls );
211 
212  // Get 1 ID and make sure getName returns correctly
213  $fooId = $store->acquireId( 'foo' );
214  $this->assertSame( 'foo', $store->getName( $fooId ) );
215 
216  // Get another ID and make sure getName returns correctly
217  $barId = $store->acquireId( 'bar' );
218  $this->assertSame( 'bar', $store->getName( $barId ) );
219 
220  // Blitz the cache and make sure it still returns
221  TestingAccessWrapper::newFromObject( $store )->tableCache = null;
222  $this->assertSame( 'foo', $store->getName( $fooId ) );
223  $this->assertSame( 'bar', $store->getName( $barId ) );
224 
225  // Blitz the cache again and get another ID and make sure getName returns correctly
226  TestingAccessWrapper::newFromObject( $store )->tableCache = null;
227  $bazId = $store->acquireId( 'baz' );
228  $this->assertSame( 'baz', $store->getName( $bazId ) );
229  $this->assertSame( 'baz', $store->getName( $bazId ) );
230  }
231 
232  public function testGetName_masterFallback() {
233  $store = $this->getNameTableSqlStore( new EmptyBagOStuff(), 1, 2 );
234 
235  // Insert a new name
236  $fooId = $store->acquireId( 'foo' );
237 
238  // Empty the process cache, getCachedTable() will now return this empty array
239  TestingAccessWrapper::newFromObject( $store )->tableCache = [];
240 
241  // getName should fallback to master, which is why we assert 2 selectCalls above
242  $this->assertSame( 'foo', $store->getName( $fooId ) );
243  }
244 
245  public function testGetMap_empty() {
246  $this->populateTable( [] );
247  $store = $this->getNameTableSqlStore( new HashBagOStuff(), 0, 1 );
248  $table = $store->getMap();
249  $this->assertSame( [], $table );
250  }
251 
252  public function testGetMap_twoValues() {
253  $this->populateTable( [ 'foo', 'bar' ] );
254  $store = $this->getNameTableSqlStore( new HashBagOStuff(), 0, 1 );
255 
256  // We are using a cache, so 2 calls should only result in 1 select on the db
257  $store->getMap();
258  $table = $store->getMap();
259 
260  $expected = [ 1 => 'foo', 2 => 'bar' ];
261  $this->assertSame( $expected, $table );
262  // Make sure the table returned is the same as the cached table
263  $this->assertSame( $expected, TestingAccessWrapper::newFromObject( $store )->tableCache );
264  }
265 
266  public function testCacheRaceCondition() {
267  $wanHashBag = new HashBagOStuff();
268  $store1 = $this->getNameTableSqlStore( $wanHashBag, 1, 1 );
269  $store2 = $this->getNameTableSqlStore( $wanHashBag, 1, 0 );
270  $store3 = $this->getNameTableSqlStore( $wanHashBag, 1, 1 );
271 
272  // Cache the current table in the instances we will use
273  // This simulates multiple requests running simultaneously
274  $store1->getMap();
275  $store2->getMap();
276  $store3->getMap();
277 
278  // Store 2 separate names using different instances
279  $fooId = $store1->acquireId( 'foo' );
280  $barId = $store2->acquireId( 'bar' );
281 
282  // Each of these instances should be aware of what they have inserted
283  $this->assertSame( $fooId, $store1->acquireId( 'foo' ) );
284  $this->assertSame( $barId, $store2->acquireId( 'bar' ) );
285 
286  // A new store should be able to get both of these new Ids
287  // Note: before there was a race condition here where acquireId( 'bar' ) would update the
288  // cache with data missing the 'foo' key that it was not aware of
289  $store4 = $this->getNameTableSqlStore( $wanHashBag, 0, 1 );
290  $this->assertSame( $fooId, $store4->getId( 'foo' ) );
291  $this->assertSame( $barId, $store4->getId( 'bar' ) );
292 
293  // If a store with old cached data tries to acquire these we will get the same ids.
294  $this->assertSame( $fooId, $store3->acquireId( 'foo' ) );
295  $this->assertSame( $barId, $store3->acquireId( 'bar' ) );
296  }
297 
298 }
MediaWiki\Tests\Storage\NameTableStoreTest\provideTestGetAndAcquireIdNameNormalization
provideTestGetAndAcquireIdNameNormalization()
Definition: NameTableStoreTest.php:164
MediaWiki\Tests\Storage\NameTableStoreTest\testGetName
testGetName( $cacheBag, $insertCalls, $selectCalls)
provideGetName
Definition: NameTableStoreTest.php:209
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:48
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
HashBagOStuff
Simple store for keeping values in an associative array for the current process.
Definition: HashBagOStuff.php:31
EmptyBagOStuff
A BagOStuff object with no objects in it.
Definition: EmptyBagOStuff.php:29
MediaWiki\Tests\Storage\NameTableStoreTest\testGetMap_empty
testGetMap_empty()
Definition: NameTableStoreTest.php:245
MediaWiki\Tests\Storage\NameTableStoreTest\provideGetAndAcquireId
provideGetAndAcquireId()
Definition: NameTableStoreTest.php:97
MediaWiki\Tests\Storage\NameTableStoreTest\getMockLoadBalancer
getMockLoadBalancer( $db)
Definition: NameTableStoreTest.php:45
BagOStuff
interface is intended to be more or less compatible with the PHP memcached client.
Definition: BagOStuff.php:47
MediaWiki\Tests\Storage\NameTableStoreTest\provideGetName
provideGetName()
Definition: NameTableStoreTest.php:199
$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! 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! 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:1993
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:37
MediaWiki\Tests\Storage
Definition: BlobStoreFactoryTest.php:3
MediaWiki\Tests\Storage\NameTableStoreTest\getCallCheckingDb
getCallCheckingDb( $insertCalls, $selectCalls)
Definition: NameTableStoreTest.php:55
MediaWiki\Tests\Storage\NameTableStoreTest
Definition: NameTableStoreTest.php:22
MediaWikiTestCase
Definition: MediaWikiTestCase.php:17
MediaWiki\Tests\Storage\NameTableStoreTest\getHashWANObjectCache
getHashWANObjectCache( $cacheBag)
Definition: NameTableStoreTest.php:37
MediaWiki\Tests\Storage\NameTableStoreTest\setUp
setUp()
Definition: NameTableStoreTest.php:24
MediaWiki\Tests\Storage\NameTableStoreTest\testCacheRaceCondition
testCacheRaceCondition()
Definition: NameTableStoreTest.php:266
Wikimedia\Rdbms\LoadBalancer
Database connection, tracking, load balancing, and transaction manager for a cluster.
Definition: LoadBalancer.php:41
MediaWiki\Tests\Storage\NameTableStoreTest\testGetName_masterFallback
testGetName_masterFallback()
Definition: NameTableStoreTest.php:232
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:87
MediaWiki\Storage\NameTableStore
Definition: NameTableStore.php:35
MediaWiki\Tests\Storage\NameTableStoreTest\testGetAndAcquireIdNameNormalization
testGetAndAcquireIdNameNormalization( $nameIn, $nameOut, $normalizationCallback)
provideTestGetAndAcquireIdNameNormalization
Definition: NameTableStoreTest.php:184
MediaWiki\Tests\Storage\NameTableStoreTest\testGetAndAcquireId
testGetAndAcquireId( $cacheBag, $needsInsert, $selectCalls, $existingValues, $name, $expectedId)
provideGetAndAcquireId
Definition: NameTableStoreTest.php:131
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
MediaWiki\Tests\Storage\NameTableStoreTest\populateTable
populateTable( $values)
Definition: NameTableStoreTest.php:29
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:22
MediaWiki\Storage\NameTableAccessException
Exception representing a failure to look up a row from a name table.
Definition: NameTableAccessException.php:32
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:56
MediaWiki\Tests\Storage\NameTableStoreTest\appendDashAToString
static appendDashAToString( $string)
Definition: NameTableStoreTest.php:177
MediaWikiTestCase\$db
Database $db
Primary database.
Definition: MediaWikiTestCase.php:57
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2171
MediaWiki\Tests\Storage\NameTableStoreTest\getNameTableSqlStore
getNameTableSqlStore(BagOStuff $cacheBag, $insertCalls, $selectCalls, $normalizationCallback=null)
Definition: NameTableStoreTest.php:82
MediaWiki\Tests\Storage\NameTableStoreTest\testGetMap_twoValues
testGetMap_twoValues()
Definition: NameTableStoreTest.php:252