MediaWiki  1.33.0
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  protected function addCoreDBData() {
30  // The default implementation causes the slot_roles to already have content. Skip that.
31  }
32 
33  private function populateTable( $values ) {
34  $insertValues = [];
35  foreach ( $values as $name ) {
36  $insertValues[] = [ 'role_name' => $name ];
37  }
38  $this->db->insert( 'slot_roles', $insertValues );
39  }
40 
41  private function getHashWANObjectCache( $cacheBag ) {
42  return new WANObjectCache( [ 'cache' => $cacheBag ] );
43  }
44 
49  private function getMockLoadBalancer( $db ) {
50  $mock = $this->getMockBuilder( LoadBalancer::class )
51  ->disableOriginalConstructor()
52  ->getMock();
53  $mock->expects( $this->any() )
54  ->method( 'getConnection' )
55  ->willReturn( $db );
56  return $mock;
57  }
58 
59  private function getCallCheckingDb( $insertCalls, $selectCalls ) {
60  $mock = $this->getMockBuilder( Database::class )
61  ->disableOriginalConstructor()
62  ->getMock();
63  $mock->expects( $this->exactly( $insertCalls ) )
64  ->method( 'insert' )
65  ->willReturnCallback( function () {
66  return call_user_func_array( [ $this->db, 'insert' ], func_get_args() );
67  } );
68  $mock->expects( $this->exactly( $selectCalls ) )
69  ->method( 'select' )
70  ->willReturnCallback( function () {
71  return call_user_func_array( [ $this->db, 'select' ], func_get_args() );
72  } );
73  $mock->expects( $this->exactly( $insertCalls ) )
74  ->method( 'affectedRows' )
75  ->willReturnCallback( function () {
76  return call_user_func_array( [ $this->db, 'affectedRows' ], func_get_args() );
77  } );
78  $mock->expects( $this->any() )
79  ->method( 'insertId' )
80  ->willReturnCallback( function () {
81  return call_user_func_array( [ $this->db, 'insertId' ], func_get_args() );
82  } );
83  return $mock;
84  }
85 
86  private function getNameTableSqlStore(
87  BagOStuff $cacheBag,
88  $insertCalls,
89  $selectCalls,
90  $normalizationCallback = null,
91  $insertCallback = null
92  ) {
93  return new NameTableStore(
94  $this->getMockLoadBalancer( $this->getCallCheckingDb( $insertCalls, $selectCalls ) ),
95  $this->getHashWANObjectCache( $cacheBag ),
96  new NullLogger(),
97  'slot_roles', 'role_id', 'role_name',
98  $normalizationCallback,
99  false,
100  $insertCallback
101  );
102  }
103 
104  public function provideGetAndAcquireId() {
105  return [
106  'no wancache, empty table' =>
107  [ new EmptyBagOStuff(), true, 1, [], 'foo', 1 ],
108  'no wancache, one matching value' =>
109  [ new EmptyBagOStuff(), false, 1, [ 'foo' ], 'foo', 1 ],
110  'no wancache, one not matching value' =>
111  [ new EmptyBagOStuff(), true, 1, [ 'bar' ], 'foo', 2 ],
112  'no wancache, multiple, one matching value' =>
113  [ new EmptyBagOStuff(), false, 1, [ 'foo', 'bar' ], 'bar', 2 ],
114  'no wancache, multiple, no matching value' =>
115  [ new EmptyBagOStuff(), true, 1, [ 'foo', 'bar' ], 'baz', 3 ],
116  'wancache, empty table' =>
117  [ new HashBagOStuff(), true, 1, [], 'foo', 1 ],
118  'wancache, one matching value' =>
119  [ new HashBagOStuff(), false, 1, [ 'foo' ], 'foo', 1 ],
120  'wancache, one not matching value' =>
121  [ new HashBagOStuff(), true, 1, [ 'bar' ], 'foo', 2 ],
122  'wancache, multiple, one matching value' =>
123  [ new HashBagOStuff(), false, 1, [ 'foo', 'bar' ], 'bar', 2 ],
124  'wancache, multiple, no matching value' =>
125  [ new HashBagOStuff(), true, 1, [ 'foo', 'bar' ], 'baz', 3 ],
126  ];
127  }
128 
138  public function testGetAndAcquireId(
139  $cacheBag,
140  $needsInsert,
141  $selectCalls,
142  $existingValues,
143  $name,
144  $expectedId
145  ) {
146  // Make sure the table is empty!
147  $this->truncateTable( 'slot_roles' );
148 
149  $this->populateTable( $existingValues );
150  $store = $this->getNameTableSqlStore( $cacheBag, (int)$needsInsert, $selectCalls );
151 
152  // Some names will not initially exist
153  try {
154  $result = $store->getId( $name );
155  $this->assertSame( $expectedId, $result );
156  } catch ( NameTableAccessException $e ) {
157  if ( $needsInsert ) {
158  $this->assertTrue( true ); // Expected exception
159  } else {
160  $this->fail( 'Did not expect an exception, but got one: ' . $e->getMessage() );
161  }
162  }
163 
164  // All names should return their id here
165  $this->assertSame( $expectedId, $store->acquireId( $name ) );
166 
167  // acquireId inserted these names, so now everything should exist with getId
168  $this->assertSame( $expectedId, $store->getId( $name ) );
169 
170  // calling getId again will also still work, and not result in more selects
171  $this->assertSame( $expectedId, $store->getId( $name ) );
172  }
173 
175  yield [ 'A', 'a', 'strtolower' ];
176  yield [ 'b', 'B', 'strtoupper' ];
177  yield [
178  'X',
179  'X',
180  function ( $name ) {
181  return $name;
182  }
183  ];
184  yield [ 'ZZ', 'ZZ-a', __CLASS__ . '::appendDashAToString' ];
185  }
186 
187  public static function appendDashAToString( $string ) {
188  return $string . '-a';
189  }
190 
195  $nameIn,
196  $nameOut,
197  $normalizationCallback
198  ) {
199  $store = $this->getNameTableSqlStore(
200  new EmptyBagOStuff(),
201  1,
202  1,
203  $normalizationCallback
204  );
205  $acquiredId = $store->acquireId( $nameIn );
206  $this->assertSame( $nameOut, $store->getName( $acquiredId ) );
207  }
208 
209  public function provideGetName() {
210  return [
211  [ new HashBagOStuff(), 3, 2 ],
212  [ new EmptyBagOStuff(), 3, 3 ],
213  ];
214  }
215 
219  public function testGetName( $cacheBag, $insertCalls, $selectCalls ) {
220  // Check for operations to in-memory cache (IMC) and persistent cache (PC)
221  $store = $this->getNameTableSqlStore( $cacheBag, $insertCalls, $selectCalls );
222 
223  // Get 1 ID and make sure getName returns correctly
224  $fooId = $store->acquireId( 'foo' ); // regen PC, set IMC, update IMC, tombstone PC
225  $this->assertSame( 'foo', $store->getName( $fooId ) ); // use IMC
226 
227  // Get another ID and make sure getName returns correctly
228  $barId = $store->acquireId( 'bar' ); // update IMC, tombstone PC
229  $this->assertSame( 'bar', $store->getName( $barId ) ); // use IMC
230 
231  // Blitz the cache and make sure it still returns
232  TestingAccessWrapper::newFromObject( $store )->tableCache = null; // clear IMC
233  $this->assertSame( 'foo', $store->getName( $fooId ) ); // regen interim PC, set IMC
234  $this->assertSame( 'bar', $store->getName( $barId ) ); // use IMC
235 
236  // Blitz the cache again and get another ID and make sure getName returns correctly
237  TestingAccessWrapper::newFromObject( $store )->tableCache = null; // clear IMC
238  $bazId = $store->acquireId( 'baz' ); // set IMC using interim PC, update IMC, tombstone PC
239  $this->assertSame( 'baz', $store->getName( $bazId ) ); // uses IMC
240  $this->assertSame( 'baz', $store->getName( $bazId ) ); // uses IMC
241  }
242 
243  public function testGetName_masterFallback() {
244  $store = $this->getNameTableSqlStore( new EmptyBagOStuff(), 1, 2 );
245 
246  // Insert a new name
247  $fooId = $store->acquireId( 'foo' );
248 
249  // Empty the process cache, getCachedTable() will now return this empty array
250  TestingAccessWrapper::newFromObject( $store )->tableCache = [];
251 
252  // getName should fallback to master, which is why we assert 2 selectCalls above
253  $this->assertSame( 'foo', $store->getName( $fooId ) );
254  }
255 
256  public function testGetMap_empty() {
257  $this->populateTable( [] );
258  $store = $this->getNameTableSqlStore( new HashBagOStuff(), 0, 1 );
259  $table = $store->getMap();
260  $this->assertSame( [], $table );
261  }
262 
263  public function testGetMap_twoValues() {
264  $this->populateTable( [ 'foo', 'bar' ] );
265  $store = $this->getNameTableSqlStore( new HashBagOStuff(), 0, 1 );
266 
267  // We are using a cache, so 2 calls should only result in 1 select on the db
268  $store->getMap();
269  $table = $store->getMap();
270 
271  $expected = [ 1 => 'foo', 2 => 'bar' ];
272  $this->assertSame( $expected, $table );
273  // Make sure the table returned is the same as the cached table
274  $this->assertSame( $expected, TestingAccessWrapper::newFromObject( $store )->tableCache );
275  }
276 
277  public function testReloadMap() {
278  $this->populateTable( [ 'foo' ] );
279  $store = $this->getNameTableSqlStore( new HashBagOStuff(), 0, 2 );
280 
281  // force load
282  $this->assertCount( 1, $store->getMap() );
283 
284  // add more stuff to the table, so the cache gets out of sync
285  $this->populateTable( [ 'bar' ] );
286 
287  $expected = [ 1 => 'foo', 2 => 'bar' ];
288  $this->assertSame( $expected, $store->reloadMap() );
289  $this->assertSame( $expected, $store->getMap() );
290  }
291 
292  public function testCacheRaceCondition() {
293  $wanHashBag = new HashBagOStuff();
294  $store1 = $this->getNameTableSqlStore( $wanHashBag, 1, 1 );
295  $store2 = $this->getNameTableSqlStore( $wanHashBag, 1, 0 );
296  $store3 = $this->getNameTableSqlStore( $wanHashBag, 1, 1 );
297 
298  // Cache the current table in the instances we will use
299  // This simulates multiple requests running simultaneously
300  $store1->getMap();
301  $store2->getMap();
302  $store3->getMap();
303 
304  // Store 2 separate names using different instances
305  $fooId = $store1->acquireId( 'foo' );
306  $barId = $store2->acquireId( 'bar' );
307 
308  // Each of these instances should be aware of what they have inserted
309  $this->assertSame( $fooId, $store1->acquireId( 'foo' ) );
310  $this->assertSame( $barId, $store2->acquireId( 'bar' ) );
311 
312  // A new store should be able to get both of these new Ids
313  // Note: before there was a race condition here where acquireId( 'bar' ) would update the
314  // cache with data missing the 'foo' key that it was not aware of
315  $store4 = $this->getNameTableSqlStore( $wanHashBag, 0, 1 );
316  $this->assertSame( $fooId, $store4->getId( 'foo' ) );
317  $this->assertSame( $barId, $store4->getId( 'bar' ) );
318 
319  // If a store with old cached data tries to acquire these we will get the same ids.
320  $this->assertSame( $fooId, $store3->acquireId( 'foo' ) );
321  $this->assertSame( $barId, $store3->acquireId( 'bar' ) );
322  }
323 
325  // FIXME: fails under postgres
326  $this->markTestSkippedIfDbType( 'postgres' );
327 
328  $store = $this->getNameTableSqlStore(
329  new EmptyBagOStuff(),
330  1,
331  1,
332  null,
333  function ( $insertFields ) {
334  $insertFields['role_id'] = 7251;
335  return $insertFields;
336  }
337  );
338  $this->assertSame( 7251, $store->acquireId( 'A' ) );
339  }
340 
341 }
MediaWiki\Tests\Storage\NameTableStoreTest\provideTestGetAndAcquireIdNameNormalization
provideTestGetAndAcquireIdNameNormalization()
Definition: NameTableStoreTest.php:174
MediaWiki\Tests\Storage\NameTableStoreTest\testGetName
testGetName( $cacheBag, $insertCalls, $selectCalls)
provideGetName
Definition: NameTableStoreTest.php:219
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:48
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
$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. '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. '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 '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:1983
MediaWiki\Tests\Storage\NameTableStoreTest\testGetMap_empty
testGetMap_empty()
Definition: NameTableStoreTest.php:256
MediaWiki\Tests\Storage\NameTableStoreTest\provideGetAndAcquireId
provideGetAndAcquireId()
Definition: NameTableStoreTest.php:104
MediaWiki\Tests\Storage\NameTableStoreTest\getMockLoadBalancer
getMockLoadBalancer( $db)
Definition: NameTableStoreTest.php:49
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:58
MediaWiki\Tests\Storage\NameTableStoreTest\provideGetName
provideGetName()
Definition: NameTableStoreTest.php:209
MediaWiki\Tests\Storage\NameTableStoreTest\testGetAndAcquireIdInsertCallback
testGetAndAcquireIdInsertCallback()
Definition: NameTableStoreTest.php:324
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
MediaWiki\Tests\Storage
Definition: BlobStoreFactoryTest.php:3
MediaWikiTestCase\truncateTable
truncateTable( $tableName, IDatabase $db=null)
Empties the given table and resets any auto-increment counters.
Definition: MediaWikiTestCase.php:1834
MediaWiki\Tests\Storage\NameTableStoreTest\getCallCheckingDb
getCallCheckingDb( $insertCalls, $selectCalls)
Definition: NameTableStoreTest.php:59
MediaWiki\Tests\Storage\NameTableStoreTest
Definition: NameTableStoreTest.php:22
MediaWikiTestCase
Definition: MediaWikiTestCase.php:17
MediaWiki\Tests\Storage\NameTableStoreTest\testReloadMap
testReloadMap()
Definition: NameTableStoreTest.php:277
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
MediaWiki\Tests\Storage\NameTableStoreTest\addCoreDBData
addCoreDBData()
Definition: NameTableStoreTest.php:29
MediaWiki\Tests\Storage\NameTableStoreTest\getHashWANObjectCache
getHashWANObjectCache( $cacheBag)
Definition: NameTableStoreTest.php:41
MediaWiki\Tests\Storage\NameTableStoreTest\setUp
setUp()
Definition: NameTableStoreTest.php:24
MediaWiki\Tests\Storage\NameTableStoreTest\testCacheRaceCondition
testCacheRaceCondition()
Definition: NameTableStoreTest.php:292
Wikimedia\Rdbms\LoadBalancer
Database connection, tracking, load balancing, and transaction manager for a cluster.
Definition: LoadBalancer.php:41
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
any
they could even be mouse clicks or menu items whatever suits your program You should also get your if any
Definition: COPYING.txt:326
MediaWiki\Tests\Storage\NameTableStoreTest\getNameTableSqlStore
getNameTableSqlStore(BagOStuff $cacheBag, $insertCalls, $selectCalls, $normalizationCallback=null, $insertCallback=null)
Definition: NameTableStoreTest.php:86
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2162
MediaWiki\Tests\Storage\NameTableStoreTest\testGetName_masterFallback
testGetName_masterFallback()
Definition: NameTableStoreTest.php:243
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:116
MediaWiki\Storage\NameTableStore
Definition: NameTableStore.php:35
MediaWiki\Tests\Storage\NameTableStoreTest\testGetAndAcquireIdNameNormalization
testGetAndAcquireIdNameNormalization( $nameIn, $nameOut, $normalizationCallback)
provideTestGetAndAcquireIdNameNormalization
Definition: NameTableStoreTest.php:194
MediaWiki\Tests\Storage\NameTableStoreTest\testGetAndAcquireId
testGetAndAcquireId( $cacheBag, $needsInsert, $selectCalls, $existingValues, $name, $expectedId)
provideGetAndAcquireId
Definition: NameTableStoreTest.php:138
MediaWiki\Tests\Storage\NameTableStoreTest\populateTable
populateTable( $values)
Definition: NameTableStoreTest.php:33
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:9
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:52
MediaWikiTestCase\markTestSkippedIfDbType
markTestSkippedIfDbType( $type)
Skip the test if using the specified database type.
Definition: MediaWikiTestCase.php:2303
MediaWiki\Tests\Storage\NameTableStoreTest\appendDashAToString
static appendDashAToString( $string)
Definition: NameTableStoreTest.php:187
MediaWikiTestCase\$db
Database $db
Primary database.
Definition: MediaWikiTestCase.php:61
MediaWiki\Tests\Storage\NameTableStoreTest\testGetMap_twoValues
testGetMap_twoValues()
Definition: NameTableStoreTest.php:263