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