Merge "RCFilters: Tweak opt-out preference description"
[lhc/web/wiklou.git] / tests / phpunit / includes / db / LBFactoryTest.php
1 <?php
2 /**
3 * Holds tests for LBFactory abstract MediaWiki class.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author Antoine Musso
22 * @copyright © 2013 Antoine Musso
23 * @copyright © 2013 Wikimedia Foundation Inc.
24 */
25
26 use Wikimedia\Rdbms\LBFactory;
27 use Wikimedia\Rdbms\LBFactorySimple;
28 use Wikimedia\Rdbms\LBFactoryMulti;
29 use Wikimedia\Rdbms\LoadBalancer;
30 use Wikimedia\Rdbms\ChronologyProtector;
31 use Wikimedia\Rdbms\DatabaseMysqli;
32 use Wikimedia\Rdbms\MySQLMasterPos;
33 use Wikimedia\Rdbms\DatabaseDomain;
34
35 /**
36 * @group Database
37 * @covers \Wikimedia\Rdbms\LBFactory
38 * @covers \Wikimedia\Rdbms\LBFactorySimple
39 * @covers \Wikimedia\Rdbms\LBFactoryMulti
40 */
41 class LBFactoryTest extends MediaWikiTestCase {
42
43 /**
44 * @covers MWLBFactory::getLBFactoryClass()
45 * @dataProvider getLBFactoryClassProvider
46 */
47 public function testGetLBFactoryClass( $expected, $deprecated ) {
48 $mockDB = $this->getMockBuilder( DatabaseMysqli::class )
49 ->disableOriginalConstructor()
50 ->getMock();
51
52 $config = [
53 'class' => $deprecated,
54 'connection' => $mockDB,
55 # Various other parameters required:
56 'sectionsByDB' => [],
57 'sectionLoads' => [],
58 'serverTemplate' => [],
59 ];
60
61 $this->hideDeprecated( '$wgLBFactoryConf must be updated. See RELEASE-NOTES for details' );
62 $result = MWLBFactory::getLBFactoryClass( $config );
63
64 $this->assertEquals( $expected, $result );
65 }
66
67 public function getLBFactoryClassProvider() {
68 return [
69 # Format: new class, old class
70 [ Wikimedia\Rdbms\LBFactorySimple::class, 'LBFactory_Simple' ],
71 [ Wikimedia\Rdbms\LBFactorySingle::class, 'LBFactory_Single' ],
72 [ Wikimedia\Rdbms\LBFactoryMulti::class, 'LBFactory_Multi' ],
73 [ Wikimedia\Rdbms\LBFactorySimple::class, 'LBFactorySimple' ],
74 [ Wikimedia\Rdbms\LBFactorySingle::class, 'LBFactorySingle' ],
75 [ Wikimedia\Rdbms\LBFactoryMulti::class, 'LBFactoryMulti' ],
76 ];
77 }
78
79 /**
80 * @covers \Wikimedia\Rdbms\LBFactory::getLocalDomainID()
81 * @covers \Wikimedia\Rdbms\LBFactory::resolveDomainID()
82 */
83 public function testLBFactorySimpleServer() {
84 global $wgDBserver, $wgDBname, $wgDBuser, $wgDBpassword, $wgDBtype, $wgSQLiteDataDir;
85
86 $servers = [
87 [
88 'host' => $wgDBserver,
89 'dbname' => $wgDBname,
90 'user' => $wgDBuser,
91 'password' => $wgDBpassword,
92 'type' => $wgDBtype,
93 'dbDirectory' => $wgSQLiteDataDir,
94 'load' => 0,
95 'flags' => DBO_TRX // REPEATABLE-READ for consistency
96 ],
97 ];
98
99 $factory = new LBFactorySimple( [ 'servers' => $servers ] );
100 $lb = $factory->getMainLB();
101
102 $dbw = $lb->getConnection( DB_MASTER );
103 $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
104
105 $dbr = $lb->getConnection( DB_REPLICA );
106 $this->assertTrue( $dbr->getLBInfo( 'master' ), 'DB_REPLICA also gets the master' );
107
108 $this->assertSame( 'my_test_wiki', $factory->resolveDomainID( 'my_test_wiki' ) );
109 $this->assertSame( $factory->getLocalDomainID(), $factory->resolveDomainID( false ) );
110
111 $factory->shutdown();
112 $lb->closeAll();
113 }
114
115 public function testLBFactorySimpleServers() {
116 global $wgDBserver, $wgDBname, $wgDBuser, $wgDBpassword, $wgDBtype, $wgSQLiteDataDir;
117
118 $servers = [
119 [ // master
120 'host' => $wgDBserver,
121 'dbname' => $wgDBname,
122 'user' => $wgDBuser,
123 'password' => $wgDBpassword,
124 'type' => $wgDBtype,
125 'dbDirectory' => $wgSQLiteDataDir,
126 'load' => 0,
127 'flags' => DBO_TRX // REPEATABLE-READ for consistency
128 ],
129 [ // emulated replica
130 'host' => $wgDBserver,
131 'dbname' => $wgDBname,
132 'user' => $wgDBuser,
133 'password' => $wgDBpassword,
134 'type' => $wgDBtype,
135 'dbDirectory' => $wgSQLiteDataDir,
136 'load' => 100,
137 'flags' => DBO_TRX // REPEATABLE-READ for consistency
138 ]
139 ];
140
141 $factory = new LBFactorySimple( [
142 'servers' => $servers,
143 'loadMonitorClass' => LoadMonitorNull::class
144 ] );
145 $lb = $factory->getMainLB();
146
147 $dbw = $lb->getConnection( DB_MASTER );
148 $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
149 $this->assertEquals(
150 ( $wgDBserver != '' ) ? $wgDBserver : 'localhost',
151 $dbw->getLBInfo( 'clusterMasterHost' ),
152 'cluster master set' );
153
154 $dbr = $lb->getConnection( DB_REPLICA );
155 $this->assertTrue( $dbr->getLBInfo( 'replica' ), 'replica shows as replica' );
156 $this->assertEquals(
157 ( $wgDBserver != '' ) ? $wgDBserver : 'localhost',
158 $dbr->getLBInfo( 'clusterMasterHost' ),
159 'cluster master set' );
160
161 $factory->shutdown();
162 $lb->closeAll();
163 }
164
165 public function testLBFactoryMultiConns() {
166 $factory = $this->newLBFactoryMultiLBs();
167
168 $dbw = $factory->getMainLB()->getConnection( DB_MASTER );
169 $this->assertTrue( $dbw->getLBInfo( 'master' ), 'master shows as master' );
170
171 $dbr = $factory->getMainLB()->getConnection( DB_REPLICA );
172 $this->assertTrue( $dbr->getLBInfo( 'replica' ), 'replica shows as replica' );
173
174 // Destructor should trigger without round stage errors
175 unset( $factory );
176 }
177
178 public function testLBFactoryMultiRoundCallbacks() {
179 $called = 0;
180 $countLBsFunc = function ( LBFactoryMulti $factory ) {
181 $count = 0;
182 $factory->forEachLB( function () use ( &$count ) {
183 ++$count;
184 } );
185
186 return $count;
187 };
188
189 $factory = $this->newLBFactoryMultiLBs();
190 $this->assertEquals( 0, $countLBsFunc( $factory ) );
191 $dbw = $factory->getMainLB()->getConnection( DB_MASTER );
192 $this->assertEquals( 1, $countLBsFunc( $factory ) );
193 // Test that LoadBalancer instances made during pre-commit callbacks in do not
194 // throw DBTransactionError due to transaction ROUND_* stages being mismatched.
195 $factory->beginMasterChanges( __METHOD__ );
196 $dbw->onTransactionPreCommitOrIdle( function () use ( $factory, &$called ) {
197 ++$called;
198 // Trigger s1 LoadBalancer instantiation during "finalize" stage.
199 // There is no s1wiki DB to select so it is not in getConnection(),
200 // but this fools getMainLB() at least.
201 $factory->getMainLB( 's1wiki' )->getConnection( DB_MASTER );
202 } );
203 $factory->commitMasterChanges( __METHOD__ );
204 $this->assertEquals( 1, $called );
205 $this->assertEquals( 2, $countLBsFunc( $factory ) );
206 $factory->shutdown();
207 $factory->closeAll();
208
209 $called = 0;
210 $factory = $this->newLBFactoryMultiLBs();
211 $this->assertEquals( 0, $countLBsFunc( $factory ) );
212 $dbw = $factory->getMainLB()->getConnection( DB_MASTER );
213 $this->assertEquals( 1, $countLBsFunc( $factory ) );
214 // Test that LoadBalancer instances made during pre-commit callbacks in do not
215 // throw DBTransactionError due to transaction ROUND_* stages being mismatched.hrow
216 // DBTransactionError due to transaction ROUND_* stages being mismatched.
217 $factory->beginMasterChanges( __METHOD__ );
218 $dbw->query( "SELECT 1 as t", __METHOD__ );
219 $dbw->onTransactionResolution( function () use ( $factory, &$called ) {
220 ++$called;
221 // Trigger s1 LoadBalancer instantiation during "finalize" stage.
222 // There is no s1wiki DB to select so it is not in getConnection(),
223 // but this fools getMainLB() at least.
224 $factory->getMainLB( 's1wiki' )->getConnection( DB_MASTER );
225 } );
226 $factory->commitMasterChanges( __METHOD__ );
227 $this->assertEquals( 1, $called );
228 $this->assertEquals( 2, $countLBsFunc( $factory ) );
229 $factory->shutdown();
230 $factory->closeAll();
231
232 $factory = $this->newLBFactoryMultiLBs();
233 $dbw = $factory->getMainLB()->getConnection( DB_MASTER );
234 // DBTransactionError should not be thrown
235 $ran = 0;
236 $dbw->onTransactionPreCommitOrIdle( function () use ( &$ran ) {
237 ++$ran;
238 } );
239 $factory->commitAll( __METHOD__ );
240 $this->assertEquals( 1, $ran );
241
242 $factory->shutdown();
243 $factory->closeAll();
244 }
245
246 private function newLBFactoryMultiLBs() {
247 global $wgDBserver, $wgDBname, $wgDBuser, $wgDBpassword, $wgDBtype, $wgSQLiteDataDir;
248
249 return new LBFactoryMulti( [
250 'sectionsByDB' => [
251 's1wiki' => 's1',
252 ],
253 'sectionLoads' => [
254 's1' => [
255 'test-db3' => 0,
256 'test-db4' => 100,
257 ],
258 'DEFAULT' => [
259 'test-db1' => 0,
260 'test-db2' => 100,
261 ]
262 ],
263 'serverTemplate' => [
264 'dbname' => $wgDBname,
265 'user' => $wgDBuser,
266 'password' => $wgDBpassword,
267 'type' => $wgDBtype,
268 'dbDirectory' => $wgSQLiteDataDir,
269 'flags' => DBO_DEFAULT
270 ],
271 'hostsByName' => [
272 'test-db1' => $wgDBserver,
273 'test-db2' => $wgDBserver,
274 'test-db3' => $wgDBserver,
275 'test-db4' => $wgDBserver
276 ],
277 'loadMonitorClass' => LoadMonitorNull::class
278 ] );
279 }
280
281 /**
282 * @covers \Wikimedia\Rdbms\ChronologyProtector
283 */
284 public function testChronologyProtector() {
285 $now = microtime( true );
286
287 // (a) First HTTP request
288 $m1Pos = new MySQLMasterPos( 'db1034-bin.000976/843431247', $now );
289 $m2Pos = new MySQLMasterPos( 'db1064-bin.002400/794074907', $now );
290
291 // Master DB 1
292 $mockDB1 = $this->getMockBuilder( DatabaseMysqli::class )
293 ->disableOriginalConstructor()
294 ->getMock();
295 $mockDB1->method( 'writesOrCallbacksPending' )->willReturn( true );
296 $mockDB1->method( 'lastDoneWrites' )->willReturn( $now );
297 $mockDB1->method( 'getMasterPos' )->willReturn( $m1Pos );
298 // Load balancer for master DB 1
299 $lb1 = $this->getMockBuilder( LoadBalancer::class )
300 ->disableOriginalConstructor()
301 ->getMock();
302 $lb1->method( 'getConnection' )->willReturn( $mockDB1 );
303 $lb1->method( 'getServerCount' )->willReturn( 2 );
304 $lb1->method( 'getAnyOpenConnection' )->willReturn( $mockDB1 );
305 $lb1->method( 'hasOrMadeRecentMasterChanges' )->will( $this->returnCallback(
306 function () use ( $mockDB1 ) {
307 $p = 0;
308 $p |= call_user_func( [ $mockDB1, 'writesOrCallbacksPending' ] );
309 $p |= call_user_func( [ $mockDB1, 'lastDoneWrites' ] );
310
311 return (bool)$p;
312 }
313 ) );
314 $lb1->method( 'getMasterPos' )->willReturn( $m1Pos );
315 $lb1->method( 'getServerName' )->with( 0 )->willReturn( 'master1' );
316 // Master DB 2
317 $mockDB2 = $this->getMockBuilder( DatabaseMysqli::class )
318 ->disableOriginalConstructor()
319 ->getMock();
320 $mockDB2->method( 'writesOrCallbacksPending' )->willReturn( true );
321 $mockDB2->method( 'lastDoneWrites' )->willReturn( $now );
322 $mockDB2->method( 'getMasterPos' )->willReturn( $m2Pos );
323 // Load balancer for master DB 2
324 $lb2 = $this->getMockBuilder( LoadBalancer::class )
325 ->disableOriginalConstructor()
326 ->getMock();
327 $lb2->method( 'getConnection' )->willReturn( $mockDB2 );
328 $lb2->method( 'getServerCount' )->willReturn( 2 );
329 $lb2->method( 'getAnyOpenConnection' )->willReturn( $mockDB2 );
330 $lb2->method( 'hasOrMadeRecentMasterChanges' )->will( $this->returnCallback(
331 function () use ( $mockDB2 ) {
332 $p = 0;
333 $p |= call_user_func( [ $mockDB2, 'writesOrCallbacksPending' ] );
334 $p |= call_user_func( [ $mockDB2, 'lastDoneWrites' ] );
335
336 return (bool)$p;
337 }
338 ) );
339 $lb2->method( 'getMasterPos' )->willReturn( $m2Pos );
340 $lb2->method( 'getServerName' )->with( 0 )->willReturn( 'master2' );
341
342 $bag = new HashBagOStuff();
343 $cp = new ChronologyProtector(
344 $bag,
345 [
346 'ip' => '127.0.0.1',
347 'agent' => "Totally-Not-FireFox"
348 ]
349 );
350
351 $mockDB1->expects( $this->exactly( 1 ) )->method( 'writesOrCallbacksPending' );
352 $mockDB1->expects( $this->exactly( 1 ) )->method( 'lastDoneWrites' );
353 $mockDB2->expects( $this->exactly( 1 ) )->method( 'writesOrCallbacksPending' );
354 $mockDB2->expects( $this->exactly( 1 ) )->method( 'lastDoneWrites' );
355
356 // Nothing to wait for on first HTTP request start
357 $cp->initLB( $lb1 );
358 $cp->initLB( $lb2 );
359 // Record positions in stash on first HTTP request end
360 $cp->shutdownLB( $lb1 );
361 $cp->shutdownLB( $lb2 );
362 $cpIndex = null;
363 $cp->shutdown( null, 'sync', $cpIndex );
364
365 $this->assertEquals( 1, $cpIndex, "CP write index set" );
366
367 // (b) Second HTTP request
368
369 // Load balancer for master DB 1
370 $lb1 = $this->getMockBuilder( LoadBalancer::class )
371 ->disableOriginalConstructor()
372 ->getMock();
373 $lb1->method( 'getServerCount' )->willReturn( 2 );
374 $lb1->method( 'getServerName' )->with( 0 )->willReturn( 'master1' );
375 $lb1->expects( $this->once() )
376 ->method( 'waitFor' )->with( $this->equalTo( $m1Pos ) );
377 // Load balancer for master DB 2
378 $lb2 = $this->getMockBuilder( LoadBalancer::class )
379 ->disableOriginalConstructor()
380 ->getMock();
381 $lb2->method( 'getServerCount' )->willReturn( 2 );
382 $lb2->method( 'getServerName' )->with( 0 )->willReturn( 'master2' );
383 $lb2->expects( $this->once() )
384 ->method( 'waitFor' )->with( $this->equalTo( $m2Pos ) );
385
386 $cp = new ChronologyProtector(
387 $bag,
388 [
389 'ip' => '127.0.0.1',
390 'agent' => "Totally-Not-FireFox"
391 ],
392 $cpIndex
393 );
394
395 // Wait for last positions to be reached on second HTTP request start
396 $cp->initLB( $lb1 );
397 $cp->initLB( $lb2 );
398 // Shutdown (nothing to record)
399 $cp->shutdownLB( $lb1 );
400 $cp->shutdownLB( $lb2 );
401 $cpIndex = null;
402 $cp->shutdown( null, 'sync', $cpIndex );
403
404 $this->assertEquals( null, $cpIndex, "CP write index retained" );
405
406 $this->assertEquals( '45e93a9c215c031d38b7c42d8e4700ca', $cp->getClientId() );
407 }
408
409 private function newLBFactoryMulti( array $baseOverride = [], array $serverOverride = [] ) {
410 global $wgDBserver, $wgDBuser, $wgDBpassword, $wgDBname, $wgDBprefix, $wgDBtype;
411 global $wgSQLiteDataDir;
412
413 return new LBFactoryMulti( $baseOverride + [
414 'sectionsByDB' => [],
415 'sectionLoads' => [
416 'DEFAULT' => [
417 'test-db1' => 1,
418 ],
419 ],
420 'serverTemplate' => $serverOverride + [
421 'dbname' => $wgDBname,
422 'tablePrefix' => $wgDBprefix,
423 'user' => $wgDBuser,
424 'password' => $wgDBpassword,
425 'type' => $wgDBtype,
426 'dbDirectory' => $wgSQLiteDataDir,
427 'flags' => DBO_DEFAULT
428 ],
429 'hostsByName' => [
430 'test-db1' => $wgDBserver,
431 ],
432 'loadMonitorClass' => LoadMonitorNull::class,
433 'localDomain' => new DatabaseDomain( $wgDBname, null, $wgDBprefix ),
434 'agent' => 'MW-UNIT-TESTS'
435 ] );
436 }
437
438 public function testNiceDomains() {
439 global $wgDBname;
440
441 if ( wfGetDB( DB_MASTER )->databasesAreIndependent() ) {
442 self::markTestSkipped( "Skipping tests about selecting DBs: not applicable" );
443 return;
444 }
445
446 $factory = $this->newLBFactoryMulti(
447 [],
448 []
449 );
450 $lb = $factory->getMainLB();
451
452 $db = $lb->getConnectionRef( DB_MASTER );
453 $this->assertEquals(
454 wfWikiID(),
455 $db->getDomainID()
456 );
457 unset( $db );
458
459 /** @var Database $db */
460 $db = $lb->getConnection( DB_MASTER, [], '' );
461
462 $this->assertEquals(
463 '',
464 $db->getDomainId(),
465 'Null domain ID handle used'
466 );
467 $this->assertEquals(
468 '',
469 $db->getDBname(),
470 'Null domain ID handle used'
471 );
472 $this->assertEquals(
473 '',
474 $db->tablePrefix(),
475 'Main domain ID handle used; prefix is empty though'
476 );
477 $this->assertEquals(
478 $this->quoteTable( $db, 'page' ),
479 $db->tableName( 'page' ),
480 "Correct full table name"
481 );
482 $this->assertEquals(
483 $this->quoteTable( $db, $wgDBname ) . '.' . $this->quoteTable( $db, 'page' ),
484 $db->tableName( "$wgDBname.page" ),
485 "Correct full table name"
486 );
487 $this->assertEquals(
488 $this->quoteTable( $db, 'nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
489 $db->tableName( 'nice_db.page' ),
490 "Correct full table name"
491 );
492
493 $lb->reuseConnection( $db ); // don't care
494
495 $db = $lb->getConnection( DB_MASTER ); // local domain connection
496 $factory->setLocalDomainPrefix( 'my_' );
497
498 $this->assertEquals( $wgDBname, $db->getDBname() );
499 $this->assertEquals(
500 "$wgDBname-my_",
501 $db->getDomainID()
502 );
503 $this->assertEquals(
504 $this->quoteTable( $db, 'my_page' ),
505 $db->tableName( 'page' ),
506 "Correct full table name"
507 );
508 $this->assertEquals(
509 $this->quoteTable( $db, 'other_nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
510 $db->tableName( 'other_nice_db.page' ),
511 "Correct full table name"
512 );
513
514 $factory->closeAll();
515 $factory->destroy();
516 }
517
518 public function testTrickyDomain() {
519 global $wgDBname;
520
521 if ( wfGetDB( DB_MASTER )->databasesAreIndependent() ) {
522 self::markTestSkipped( "Skipping tests about selecting DBs: not applicable" );
523 return;
524 }
525
526 $dbname = 'unittest-domain'; // explodes if DB is selected
527 $factory = $this->newLBFactoryMulti(
528 [ 'localDomain' => ( new DatabaseDomain( $dbname, null, '' ) )->getId() ],
529 [
530 'dbName' => 'do_not_select_me' // explodes if DB is selected
531 ]
532 );
533 $lb = $factory->getMainLB();
534 /** @var Database $db */
535 $db = $lb->getConnection( DB_MASTER, [], '' );
536
537 $this->assertEquals( '', $db->getDomainID(), "Null domain used" );
538
539 $this->assertEquals(
540 $this->quoteTable( $db, 'page' ),
541 $db->tableName( 'page' ),
542 "Correct full table name"
543 );
544
545 $this->assertEquals(
546 $this->quoteTable( $db, $dbname ) . '.' . $this->quoteTable( $db, 'page' ),
547 $db->tableName( "$dbname.page" ),
548 "Correct full table name"
549 );
550
551 $this->assertEquals(
552 $this->quoteTable( $db, 'nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
553 $db->tableName( 'nice_db.page' ),
554 "Correct full table name"
555 );
556
557 $lb->reuseConnection( $db ); // don't care
558
559 $factory->setLocalDomainPrefix( 'my_' );
560 $db = $lb->getConnection( DB_MASTER, [], "$wgDBname-my_" );
561
562 $this->assertEquals(
563 $this->quoteTable( $db, 'my_page' ),
564 $db->tableName( 'page' ),
565 "Correct full table name"
566 );
567 $this->assertEquals(
568 $this->quoteTable( $db, 'other_nice_db' ) . '.' . $this->quoteTable( $db, 'page' ),
569 $db->tableName( 'other_nice_db.page' ),
570 "Correct full table name"
571 );
572 $this->assertEquals(
573 $this->quoteTable( $db, 'garbage-db' ) . '.' . $this->quoteTable( $db, 'page' ),
574 $db->tableName( 'garbage-db.page' ),
575 "Correct full table name"
576 );
577
578 $lb->reuseConnection( $db ); // don't care
579
580 $factory->closeAll();
581 $factory->destroy();
582 }
583
584 public function testInvalidSelectDB() {
585 // FIXME: fails under sqlite
586 $this->markTestSkippedIfDbType( 'sqlite' );
587 $dbname = 'unittest-domain'; // explodes if DB is selected
588 $factory = $this->newLBFactoryMulti(
589 [ 'localDomain' => ( new DatabaseDomain( $dbname, null, '' ) )->getId() ],
590 [
591 'dbName' => 'do_not_select_me' // explodes if DB is selected
592 ]
593 );
594 $lb = $factory->getMainLB();
595 /** @var Database $db */
596 $db = $lb->getConnection( DB_MASTER, [], '' );
597
598 if ( $db->getType() === 'sqlite' ) {
599 $this->assertFalse( $db->selectDB( 'garbage-db' ) );
600 } elseif ( $db->databasesAreIndependent() ) {
601 try {
602 $e = null;
603 $db->selectDB( 'garbage-db' );
604 } catch ( \Wikimedia\Rdbms\DBConnectionError $e ) {
605 // expected
606 }
607 $this->assertInstanceOf( \Wikimedia\Rdbms\DBConnectionError::class, $e );
608 $this->assertFalse( $db->isOpen() );
609 } else {
610 \Wikimedia\suppressWarnings();
611 try {
612 $this->assertFalse( $db->selectDB( 'garbage-db' ) );
613 $this->fail( "No error thrown." );
614 } catch ( \Wikimedia\Rdbms\DBExpectedError $e ) {
615 $this->assertEquals(
616 "Could not select database 'garbage-db'.",
617 $e->getMessage()
618 );
619 }
620 \Wikimedia\restoreWarnings();
621 }
622 }
623
624 public function testRedefineLocalDomain() {
625 global $wgDBname;
626
627 if ( wfGetDB( DB_MASTER )->databasesAreIndependent() ) {
628 self::markTestSkipped( "Skipping tests about selecting DBs: not applicable" );
629 return;
630 }
631
632 $factory = $this->newLBFactoryMulti(
633 [],
634 []
635 );
636 $lb = $factory->getMainLB();
637
638 $conn1 = $lb->getConnectionRef( DB_MASTER );
639 $this->assertEquals(
640 wfWikiID(),
641 $conn1->getDomainID()
642 );
643 unset( $conn1 );
644
645 $factory->redefineLocalDomain( 'somedb-prefix' );
646 $this->assertEquals( 'somedb-prefix', $factory->getLocalDomainID() );
647
648 $domain = new DatabaseDomain( $wgDBname, null, 'pref' );
649 $factory->redefineLocalDomain( $domain );
650
651 $n = 0;
652 $lb->forEachOpenConnection( function () use ( &$n ) {
653 ++$n;
654 } );
655 $this->assertEquals( 0, $n, "Connections closed" );
656
657 $conn2 = $lb->getConnectionRef( DB_MASTER );
658 $this->assertEquals(
659 $domain->getId(),
660 $conn2->getDomainID()
661 );
662 unset( $conn2 );
663
664 $factory->closeAll();
665 $factory->destroy();
666 }
667
668 private function quoteTable( Database $db, $table ) {
669 if ( $db->getType() === 'sqlite' ) {
670 return $table;
671 } else {
672 return $db->addIdentifierQuotes( $table );
673 }
674 }
675
676 /**
677 * @covers \Wikimedia\Rdbms\LBFactory::makeCookieValueFromCPIndex()
678 * @covers \Wikimedia\Rdbms\LBFactory::getCPInfoFromCookieValue()
679 */
680 public function testCPPosIndexCookieValues() {
681 $time = 1526522031;
682 $agentId = md5( 'Ramsey\'s Loyal Presa Canario' );
683
684 $this->assertEquals(
685 '3@542#c47dcfb0566e7d7bc110a6128a45c93a',
686 LBFactory::makeCookieValueFromCPIndex( 3, 542, $agentId )
687 );
688
689 $lbFactory = $this->newLBFactoryMulti();
690 $lbFactory->setRequestInfo( [ 'IPAddress' => '10.64.24.52', 'UserAgent' => 'meow' ] );
691 $this->assertEquals(
692 '1@542#c47dcfb0566e7d7bc110a6128a45c93a',
693 LBFactory::makeCookieValueFromCPIndex( 1, 542, $agentId )
694 );
695
696 $this->assertSame(
697 null,
698 LBFactory::getCPInfoFromCookieValue( "5#$agentId", $time - 10 )['index'],
699 'No time set'
700 );
701 $this->assertSame(
702 null,
703 LBFactory::getCPInfoFromCookieValue( "5@$time", $time - 10 )['index'],
704 'No agent set'
705 );
706 $this->assertSame(
707 null,
708 LBFactory::getCPInfoFromCookieValue( "0@$time#$agentId", $time - 10 )['index'],
709 'Bad index'
710 );
711
712 $this->assertSame(
713 2,
714 LBFactory::getCPInfoFromCookieValue( "2@$time#$agentId", $time - 10 )['index'],
715 'Fresh'
716 );
717 $this->assertSame(
718 2,
719 LBFactory::getCPInfoFromCookieValue( "2@$time#$agentId", $time + 9 - 10 )['index'],
720 'Almost stale'
721 );
722 $this->assertSame(
723 null,
724 LBFactory::getCPInfoFromCookieValue( "0@$time#$agentId", $time + 9 - 10 )['index'],
725 'Almost stale; bad index'
726 );
727 $this->assertSame(
728 null,
729 LBFactory::getCPInfoFromCookieValue( "2@$time#$agentId", $time + 11 - 10 )['index'],
730 'Stale'
731 );
732
733 $this->assertSame(
734 $agentId,
735 LBFactory::getCPInfoFromCookieValue( "5@$time#$agentId", $time - 10 )['clientId'],
736 'Live (client ID)'
737 );
738 $this->assertSame(
739 null,
740 LBFactory::getCPInfoFromCookieValue( "5@$time#$agentId", $time + 11 - 10 )['clientId'],
741 'Stale (client ID)'
742 );
743 }
744 }