Move ResultWrapper subclasses to Rdbms
[mediawiki.git] / tests / phpunit / includes / BlockTest.php
blob63d05a065315af2e97fc4a57d863fedd3588122d
1 <?php
3 /**
4 * @group Database
5 * @group Blocking
6 */
7 class BlockTest extends MediaWikiLangTestCase {
9 /** @var Block */
10 private $block;
11 private $madeAt;
13 /* variable used to save up the blockID we insert in this test suite */
14 private $blockId;
16 function addDBData() {
17 $user = User::newFromName( 'UTBlockee' );
18 if ( $user->getId() == 0 ) {
19 $user->addToDatabase();
20 TestUser::setPasswordForUser( $user, 'UTBlockeePassword' );
22 $user->saveSettings();
25 // Delete the last round's block if it's still there
26 $oldBlock = Block::newFromTarget( 'UTBlockee' );
27 if ( $oldBlock ) {
28 // An old block will prevent our new one from saving.
29 $oldBlock->delete();
32 $blockOptions = [
33 'address' => 'UTBlockee',
34 'user' => $user->getId(),
35 'reason' => 'Parce que',
36 'expiry' => time() + 100500,
38 $this->block = new Block( $blockOptions );
39 $this->madeAt = wfTimestamp( TS_MW );
41 $this->block->insert();
42 // save up ID for use in assertion. Since ID is an autoincrement,
43 // its value might change depending on the order the tests are run.
44 // ApiBlockTest insert its own blocks!
45 $newBlockId = $this->block->getId();
46 if ( $newBlockId ) {
47 $this->blockId = $newBlockId;
48 } else {
49 throw new MWException( "Failed to insert block for BlockTest; old leftover block remaining?" );
52 $this->addXffBlocks();
55 /**
56 * debug function : dump the ipblocks table
58 function dumpBlocks() {
59 $v = $this->db->select( 'ipblocks', '*' );
60 print "Got " . $v->numRows() . " rows. Full dump follow:\n";
61 foreach ( $v as $row ) {
62 print_r( $row );
66 /**
67 * @covers Block::newFromTarget
69 public function testINewFromTargetReturnsCorrectBlock() {
70 $this->assertTrue(
71 $this->block->equals( Block::newFromTarget( 'UTBlockee' ) ),
72 "newFromTarget() returns the same block as the one that was made"
76 /**
77 * @covers Block::newFromID
79 public function testINewFromIDReturnsCorrectBlock() {
80 $this->assertTrue(
81 $this->block->equals( Block::newFromID( $this->blockId ) ),
82 "newFromID() returns the same block as the one that was made"
86 /**
87 * per T28425
89 public function testBug26425BlockTimestampDefaultsToTime() {
90 // delta to stop one-off errors when things happen to go over a second mark.
91 $delta = abs( $this->madeAt - $this->block->mTimestamp );
92 $this->assertLessThan(
94 $delta,
95 "If no timestamp is specified, the block is recorded as time()"
99 /**
100 * CheckUser since being changed to use Block::newFromTarget started failing
101 * because the new function didn't accept empty strings like Block::load()
102 * had. Regression T31116.
104 * @dataProvider provideBug29116Data
105 * @covers Block::newFromTarget
107 public function testBug29116NewFromTargetWithEmptyIp( $vagueTarget ) {
108 $block = Block::newFromTarget( 'UTBlockee', $vagueTarget );
109 $this->assertTrue(
110 $this->block->equals( $block ),
111 "newFromTarget() returns the same block as the one that was made when "
112 . "given empty vagueTarget param " . var_export( $vagueTarget, true )
116 public static function provideBug29116Data() {
117 return [
118 [ null ],
119 [ '' ],
120 [ false ]
125 * @covers Block::prevents
127 public function testBlockedUserCanNotCreateAccount() {
128 $username = 'BlockedUserToCreateAccountWith';
129 $u = User::newFromName( $username );
130 $u->addToDatabase();
131 $userId = $u->getId();
132 $this->assertNotEquals( 0, $userId, 'sanity' );
133 TestUser::setPasswordForUser( $u, 'NotRandomPass' );
134 unset( $u );
136 // Sanity check
137 $this->assertNull(
138 Block::newFromTarget( $username ),
139 "$username should not be blocked"
142 // Reload user
143 $u = User::newFromName( $username );
144 $this->assertFalse(
145 $u->isBlockedFromCreateAccount(),
146 "Our sandbox user should be able to create account before being blocked"
149 // Foreign perspective (blockee not on current wiki)...
150 $blockOptions = [
151 'address' => $username,
152 'user' => $userId,
153 'reason' => 'crosswiki block...',
154 'timestamp' => wfTimestampNow(),
155 'expiry' => $this->db->getInfinity(),
156 'createAccount' => true,
157 'enableAutoblock' => true,
158 'hideName' => true,
159 'blockEmail' => true,
160 'byText' => 'MetaWikiUser',
162 $block = new Block( $blockOptions );
163 $block->insert();
165 // Reload block from DB
166 $userBlock = Block::newFromTarget( $username );
167 $this->assertTrue(
168 (bool)$block->prevents( 'createaccount' ),
169 "Block object in DB should prevents 'createaccount'"
172 $this->assertInstanceOf(
173 'Block',
174 $userBlock,
175 "'$username' block block object should be existent"
178 // Reload user
179 $u = User::newFromName( $username );
180 $this->assertTrue(
181 (bool)$u->isBlockedFromCreateAccount(),
182 "Our sandbox user '$username' should NOT be able to create account"
187 * @covers Block::insert
189 public function testCrappyCrossWikiBlocks() {
190 // Delete the last round's block if it's still there
191 $oldBlock = Block::newFromTarget( 'UserOnForeignWiki' );
192 if ( $oldBlock ) {
193 // An old block will prevent our new one from saving.
194 $oldBlock->delete();
197 // Local perspective (blockee on current wiki)...
198 $user = User::newFromName( 'UserOnForeignWiki' );
199 $user->addToDatabase();
200 $userId = $user->getId();
201 $this->assertNotEquals( 0, $userId, 'sanity' );
203 // Foreign perspective (blockee not on current wiki)...
204 $blockOptions = [
205 'address' => 'UserOnForeignWiki',
206 'user' => $user->getId(),
207 'reason' => 'crosswiki block...',
208 'timestamp' => wfTimestampNow(),
209 'expiry' => $this->db->getInfinity(),
210 'createAccount' => true,
211 'enableAutoblock' => true,
212 'hideName' => true,
213 'blockEmail' => true,
214 'byText' => 'MetaWikiUser',
216 $block = new Block( $blockOptions );
218 $res = $block->insert( $this->db );
219 $this->assertTrue( (bool)$res['id'], 'Block succeeded' );
221 $user = null; // clear
223 $block = Block::newFromID( $res['id'] );
224 $this->assertEquals(
225 'UserOnForeignWiki',
226 $block->getTarget()->getName(),
227 'Correct blockee name'
229 $this->assertEquals( $userId, $block->getTarget()->getId(), 'Correct blockee id' );
230 $this->assertEquals( 'MetaWikiUser', $block->getBlocker(), 'Correct blocker name' );
231 $this->assertEquals( 'MetaWikiUser', $block->getByName(), 'Correct blocker name' );
232 $this->assertEquals( 0, $block->getBy(), 'Correct blocker id' );
235 protected function addXffBlocks() {
236 static $inited = false;
238 if ( $inited ) {
239 return;
242 $inited = true;
244 $blockList = [
245 [ 'target' => '70.2.0.0/16',
246 'type' => Block::TYPE_RANGE,
247 'desc' => 'Range Hardblock',
248 'ACDisable' => false,
249 'isHardblock' => true,
250 'isAutoBlocking' => false,
252 [ 'target' => '2001:4860:4001::/48',
253 'type' => Block::TYPE_RANGE,
254 'desc' => 'Range6 Hardblock',
255 'ACDisable' => false,
256 'isHardblock' => true,
257 'isAutoBlocking' => false,
259 [ 'target' => '60.2.0.0/16',
260 'type' => Block::TYPE_RANGE,
261 'desc' => 'Range Softblock with AC Disabled',
262 'ACDisable' => true,
263 'isHardblock' => false,
264 'isAutoBlocking' => false,
266 [ 'target' => '50.2.0.0/16',
267 'type' => Block::TYPE_RANGE,
268 'desc' => 'Range Softblock',
269 'ACDisable' => false,
270 'isHardblock' => false,
271 'isAutoBlocking' => false,
273 [ 'target' => '50.1.1.1',
274 'type' => Block::TYPE_IP,
275 'desc' => 'Exact Softblock',
276 'ACDisable' => false,
277 'isHardblock' => false,
278 'isAutoBlocking' => false,
282 foreach ( $blockList as $insBlock ) {
283 $target = $insBlock['target'];
285 if ( $insBlock['type'] === Block::TYPE_IP ) {
286 $target = User::newFromName( IP::sanitizeIP( $target ), false )->getName();
287 } elseif ( $insBlock['type'] === Block::TYPE_RANGE ) {
288 $target = IP::sanitizeRange( $target );
291 $block = new Block();
292 $block->setTarget( $target );
293 $block->setBlocker( 'testblocker@global' );
294 $block->mReason = $insBlock['desc'];
295 $block->mExpiry = 'infinity';
296 $block->prevents( 'createaccount', $insBlock['ACDisable'] );
297 $block->isHardblock( $insBlock['isHardblock'] );
298 $block->isAutoblocking( $insBlock['isAutoBlocking'] );
299 $block->insert();
303 public static function providerXff() {
304 return [
305 [ 'xff' => '1.2.3.4, 70.2.1.1, 60.2.1.1, 2.3.4.5',
306 'count' => 2,
307 'result' => 'Range Hardblock'
309 [ 'xff' => '1.2.3.4, 50.2.1.1, 60.2.1.1, 2.3.4.5',
310 'count' => 2,
311 'result' => 'Range Softblock with AC Disabled'
313 [ 'xff' => '1.2.3.4, 70.2.1.1, 50.1.1.1, 2.3.4.5',
314 'count' => 2,
315 'result' => 'Exact Softblock'
317 [ 'xff' => '1.2.3.4, 70.2.1.1, 50.2.1.1, 50.1.1.1, 2.3.4.5',
318 'count' => 3,
319 'result' => 'Exact Softblock'
321 [ 'xff' => '1.2.3.4, 70.2.1.1, 50.2.1.1, 2.3.4.5',
322 'count' => 2,
323 'result' => 'Range Hardblock'
325 [ 'xff' => '1.2.3.4, 70.2.1.1, 60.2.1.1, 2.3.4.5',
326 'count' => 2,
327 'result' => 'Range Hardblock'
329 [ 'xff' => '50.2.1.1, 60.2.1.1, 2.3.4.5',
330 'count' => 2,
331 'result' => 'Range Softblock with AC Disabled'
333 [ 'xff' => '1.2.3.4, 50.1.1.1, 60.2.1.1, 2.3.4.5',
334 'count' => 2,
335 'result' => 'Exact Softblock'
337 [ 'xff' => '1.2.3.4, <$A_BUNCH-OF{INVALID}TEXT\>, 60.2.1.1, 2.3.4.5',
338 'count' => 1,
339 'result' => 'Range Softblock with AC Disabled'
341 [ 'xff' => '1.2.3.4, 50.2.1.1, 2001:4860:4001:802::1003, 2.3.4.5',
342 'count' => 2,
343 'result' => 'Range6 Hardblock'
349 * @dataProvider providerXff
350 * @covers Block::getBlocksForIPList
351 * @covers Block::chooseBlock
353 public function testBlocksOnXff( $xff, $exCount, $exResult ) {
354 $list = array_map( 'trim', explode( ',', $xff ) );
355 $xffblocks = Block::getBlocksForIPList( $list, true );
356 $this->assertEquals( $exCount, count( $xffblocks ), 'Number of blocks for ' . $xff );
357 $block = Block::chooseBlock( $xffblocks, $list );
358 $this->assertEquals( $exResult, $block->mReason, 'Correct block type for XFF header ' . $xff );
361 public function testDeprecatedConstructor() {
362 $this->hideDeprecated( 'Block::__construct with multiple arguments' );
363 $username = 'UnthinkablySecretRandomUsername';
364 $reason = 'being irrational';
366 # Set up the target
367 $u = User::newFromName( $username );
368 if ( $u->getId() == 0 ) {
369 $u->addToDatabase();
370 TestUser::setPasswordForUser( $u, 'TotallyObvious' );
372 unset( $u );
374 # Make sure the user isn't blocked
375 $this->assertNull(
376 Block::newFromTarget( $username ),
377 "$username should not be blocked"
380 # Perform the block
381 $block = new Block(
382 /* address */ $username,
383 /* user */ 0,
384 /* by */ 0,
385 /* reason */ $reason,
386 /* timestamp */ 0,
387 /* auto */ false,
388 /* expiry */ 0
390 $block->insert();
392 # Check target
393 $this->assertEquals(
394 $block->getTarget()->getName(),
395 $username,
396 "Target should be set properly"
399 # Check supplied parameter
400 $this->assertEquals(
401 $block->mReason,
402 $reason,
403 "Reason should be non-default"
406 # Check default parameter
407 $this->assertFalse(
408 (bool)$block->prevents( 'createaccount' ),
409 "Account creation should not be blocked by default"
413 public function testSystemBlocks() {
414 $blockOptions = [
415 'address' => 'UTBlockee',
416 'reason' => 'test system block',
417 'timestamp' => wfTimestampNow(),
418 'expiry' => $this->db->getInfinity(),
419 'byText' => 'MetaWikiUser',
420 'systemBlock' => 'test',
421 'enableAutoblock' => true,
423 $block = new Block( $blockOptions );
425 $this->assertSame( 'test', $block->getSystemBlockType() );
427 try {
428 $block->insert();
429 $this->fail( 'Expected exception not thrown' );
430 } catch ( MWException $ex ) {
431 $this->assertSame( 'Cannot insert a system block into the database', $ex->getMessage() );
434 try {
435 $block->doAutoblock( '192.0.2.2' );
436 $this->fail( 'Expected exception not thrown' );
437 } catch ( MWException $ex ) {
438 $this->assertSame( 'Cannot autoblock from a system block', $ex->getMessage() );