Add @covers tags to miscellaneous tests (#2)
[lhc/web/wiklou.git] / tests / phpunit / includes / BlockTest.php
1 <?php
2
3 /**
4 * @group Database
5 * @group Blocking
6 */
7 class BlockTest extends MediaWikiLangTestCase {
8
9 /**
10 * @return User
11 */
12 private function getUserForBlocking() {
13 $testUser = $this->getMutableTestUser();
14 $user = $testUser->getUser();
15 $user->addToDatabase();
16 TestUser::setPasswordForUser( $user, 'UTBlockeePassword' );
17 $user->saveSettings();
18 return $user;
19 }
20
21 /**
22 * @param User $user
23 *
24 * @return Block
25 * @throws MWException
26 */
27 private function addBlockForUser( User $user ) {
28 // Delete the last round's block if it's still there
29 $oldBlock = Block::newFromTarget( $user->getName() );
30 if ( $oldBlock ) {
31 // An old block will prevent our new one from saving.
32 $oldBlock->delete();
33 }
34
35 $blockOptions = [
36 'address' => $user->getName(),
37 'user' => $user->getId(),
38 'reason' => 'Parce que',
39 'expiry' => time() + 100500,
40 ];
41 $block = new Block( $blockOptions );
42
43 $block->insert();
44 // save up ID for use in assertion. Since ID is an autoincrement,
45 // its value might change depending on the order the tests are run.
46 // ApiBlockTest insert its own blocks!
47 if ( !$block->getId() ) {
48 throw new MWException( "Failed to insert block for BlockTest; old leftover block remaining?" );
49 }
50
51 $this->addXffBlocks();
52
53 return $block;
54 }
55
56 /**
57 * @covers Block::newFromTarget
58 */
59 public function testINewFromTargetReturnsCorrectBlock() {
60 $user = $this->getUserForBlocking();
61 $block = $this->addBlockForUser( $user );
62
63 $this->assertTrue(
64 $block->equals( Block::newFromTarget( $user->getName() ) ),
65 "newFromTarget() returns the same block as the one that was made"
66 );
67 }
68
69 /**
70 * @covers Block::newFromID
71 */
72 public function testINewFromIDReturnsCorrectBlock() {
73 $user = $this->getUserForBlocking();
74 $block = $this->addBlockForUser( $user );
75
76 $this->assertTrue(
77 $block->equals( Block::newFromID( $block->getId() ) ),
78 "newFromID() returns the same block as the one that was made"
79 );
80 }
81
82 /**
83 * per T28425
84 * @covers Block::__construct
85 */
86 public function testBug26425BlockTimestampDefaultsToTime() {
87 $user = $this->getUserForBlocking();
88 $block = $this->addBlockForUser( $user );
89 $madeAt = wfTimestamp( TS_MW );
90
91 // delta to stop one-off errors when things happen to go over a second mark.
92 $delta = abs( $madeAt - $block->mTimestamp );
93 $this->assertLessThan(
94 2,
95 $delta,
96 "If no timestamp is specified, the block is recorded as time()"
97 );
98 }
99
100 /**
101 * CheckUser since being changed to use Block::newFromTarget started failing
102 * because the new function didn't accept empty strings like Block::load()
103 * had. Regression T31116.
104 *
105 * @dataProvider provideBug29116Data
106 * @covers Block::newFromTarget
107 */
108 public function testBug29116NewFromTargetWithEmptyIp( $vagueTarget ) {
109 $user = $this->getUserForBlocking();
110 $initialBlock = $this->addBlockForUser( $user );
111 $block = Block::newFromTarget( $user->getName(), $vagueTarget );
112
113 $this->assertTrue(
114 $initialBlock->equals( $block ),
115 "newFromTarget() returns the same block as the one that was made when "
116 . "given empty vagueTarget param " . var_export( $vagueTarget, true )
117 );
118 }
119
120 public static function provideBug29116Data() {
121 return [
122 [ null ],
123 [ '' ],
124 [ false ]
125 ];
126 }
127
128 /**
129 * @covers Block::prevents
130 */
131 public function testBlockedUserCanNotCreateAccount() {
132 $username = 'BlockedUserToCreateAccountWith';
133 $u = User::newFromName( $username );
134 $u->addToDatabase();
135 $userId = $u->getId();
136 $this->assertNotEquals( 0, $userId, 'sanity' );
137 TestUser::setPasswordForUser( $u, 'NotRandomPass' );
138 unset( $u );
139
140 // Sanity check
141 $this->assertNull(
142 Block::newFromTarget( $username ),
143 "$username should not be blocked"
144 );
145
146 // Reload user
147 $u = User::newFromName( $username );
148 $this->assertFalse(
149 $u->isBlockedFromCreateAccount(),
150 "Our sandbox user should be able to create account before being blocked"
151 );
152
153 // Foreign perspective (blockee not on current wiki)...
154 $blockOptions = [
155 'address' => $username,
156 'user' => $userId,
157 'reason' => 'crosswiki block...',
158 'timestamp' => wfTimestampNow(),
159 'expiry' => $this->db->getInfinity(),
160 'createAccount' => true,
161 'enableAutoblock' => true,
162 'hideName' => true,
163 'blockEmail' => true,
164 'byText' => 'm>MetaWikiUser',
165 ];
166 $block = new Block( $blockOptions );
167 $block->insert();
168
169 // Reload block from DB
170 $userBlock = Block::newFromTarget( $username );
171 $this->assertTrue(
172 (bool)$block->prevents( 'createaccount' ),
173 "Block object in DB should prevents 'createaccount'"
174 );
175
176 $this->assertInstanceOf(
177 'Block',
178 $userBlock,
179 "'$username' block block object should be existent"
180 );
181
182 // Reload user
183 $u = User::newFromName( $username );
184 $this->assertTrue(
185 (bool)$u->isBlockedFromCreateAccount(),
186 "Our sandbox user '$username' should NOT be able to create account"
187 );
188 }
189
190 /**
191 * @covers Block::insert
192 */
193 public function testCrappyCrossWikiBlocks() {
194 // Delete the last round's block if it's still there
195 $oldBlock = Block::newFromTarget( 'UserOnForeignWiki' );
196 if ( $oldBlock ) {
197 // An old block will prevent our new one from saving.
198 $oldBlock->delete();
199 }
200
201 // Local perspective (blockee on current wiki)...
202 $user = User::newFromName( 'UserOnForeignWiki' );
203 $user->addToDatabase();
204 $userId = $user->getId();
205 $this->assertNotEquals( 0, $userId, 'sanity' );
206
207 // Foreign perspective (blockee not on current wiki)...
208 $blockOptions = [
209 'address' => 'UserOnForeignWiki',
210 'user' => $user->getId(),
211 'reason' => 'crosswiki block...',
212 'timestamp' => wfTimestampNow(),
213 'expiry' => $this->db->getInfinity(),
214 'createAccount' => true,
215 'enableAutoblock' => true,
216 'hideName' => true,
217 'blockEmail' => true,
218 'byText' => 'Meta>MetaWikiUser',
219 ];
220 $block = new Block( $blockOptions );
221
222 $res = $block->insert( $this->db );
223 $this->assertTrue( (bool)$res['id'], 'Block succeeded' );
224
225 $user = null; // clear
226
227 $block = Block::newFromID( $res['id'] );
228 $this->assertEquals(
229 'UserOnForeignWiki',
230 $block->getTarget()->getName(),
231 'Correct blockee name'
232 );
233 $this->assertEquals( $userId, $block->getTarget()->getId(), 'Correct blockee id' );
234 $this->assertEquals( 'Meta>MetaWikiUser', $block->getBlocker()->getName(),
235 'Correct blocker name' );
236 $this->assertEquals( 'Meta>MetaWikiUser', $block->getByName(), 'Correct blocker name' );
237 $this->assertEquals( 0, $block->getBy(), 'Correct blocker id' );
238 }
239
240 protected function addXffBlocks() {
241 static $inited = false;
242
243 if ( $inited ) {
244 return;
245 }
246
247 $inited = true;
248
249 $blockList = [
250 [ 'target' => '70.2.0.0/16',
251 'type' => Block::TYPE_RANGE,
252 'desc' => 'Range Hardblock',
253 'ACDisable' => false,
254 'isHardblock' => true,
255 'isAutoBlocking' => false,
256 ],
257 [ 'target' => '2001:4860:4001::/48',
258 'type' => Block::TYPE_RANGE,
259 'desc' => 'Range6 Hardblock',
260 'ACDisable' => false,
261 'isHardblock' => true,
262 'isAutoBlocking' => false,
263 ],
264 [ 'target' => '60.2.0.0/16',
265 'type' => Block::TYPE_RANGE,
266 'desc' => 'Range Softblock with AC Disabled',
267 'ACDisable' => true,
268 'isHardblock' => false,
269 'isAutoBlocking' => false,
270 ],
271 [ 'target' => '50.2.0.0/16',
272 'type' => Block::TYPE_RANGE,
273 'desc' => 'Range Softblock',
274 'ACDisable' => false,
275 'isHardblock' => false,
276 'isAutoBlocking' => false,
277 ],
278 [ 'target' => '50.1.1.1',
279 'type' => Block::TYPE_IP,
280 'desc' => 'Exact Softblock',
281 'ACDisable' => false,
282 'isHardblock' => false,
283 'isAutoBlocking' => false,
284 ],
285 ];
286
287 $blocker = $this->getTestUser()->getUser();
288 foreach ( $blockList as $insBlock ) {
289 $target = $insBlock['target'];
290
291 if ( $insBlock['type'] === Block::TYPE_IP ) {
292 $target = User::newFromName( IP::sanitizeIP( $target ), false )->getName();
293 } elseif ( $insBlock['type'] === Block::TYPE_RANGE ) {
294 $target = IP::sanitizeRange( $target );
295 }
296
297 $block = new Block();
298 $block->setTarget( $target );
299 $block->setBlocker( $blocker );
300 $block->mReason = $insBlock['desc'];
301 $block->mExpiry = 'infinity';
302 $block->prevents( 'createaccount', $insBlock['ACDisable'] );
303 $block->isHardblock( $insBlock['isHardblock'] );
304 $block->isAutoblocking( $insBlock['isAutoBlocking'] );
305 $block->insert();
306 }
307 }
308
309 public static function providerXff() {
310 return [
311 [ 'xff' => '1.2.3.4, 70.2.1.1, 60.2.1.1, 2.3.4.5',
312 'count' => 2,
313 'result' => 'Range Hardblock'
314 ],
315 [ 'xff' => '1.2.3.4, 50.2.1.1, 60.2.1.1, 2.3.4.5',
316 'count' => 2,
317 'result' => 'Range Softblock with AC Disabled'
318 ],
319 [ 'xff' => '1.2.3.4, 70.2.1.1, 50.1.1.1, 2.3.4.5',
320 'count' => 2,
321 'result' => 'Exact Softblock'
322 ],
323 [ 'xff' => '1.2.3.4, 70.2.1.1, 50.2.1.1, 50.1.1.1, 2.3.4.5',
324 'count' => 3,
325 'result' => 'Exact Softblock'
326 ],
327 [ 'xff' => '1.2.3.4, 70.2.1.1, 50.2.1.1, 2.3.4.5',
328 'count' => 2,
329 'result' => 'Range Hardblock'
330 ],
331 [ 'xff' => '1.2.3.4, 70.2.1.1, 60.2.1.1, 2.3.4.5',
332 'count' => 2,
333 'result' => 'Range Hardblock'
334 ],
335 [ 'xff' => '50.2.1.1, 60.2.1.1, 2.3.4.5',
336 'count' => 2,
337 'result' => 'Range Softblock with AC Disabled'
338 ],
339 [ 'xff' => '1.2.3.4, 50.1.1.1, 60.2.1.1, 2.3.4.5',
340 'count' => 2,
341 'result' => 'Exact Softblock'
342 ],
343 [ 'xff' => '1.2.3.4, <$A_BUNCH-OF{INVALID}TEXT\>, 60.2.1.1, 2.3.4.5',
344 'count' => 1,
345 'result' => 'Range Softblock with AC Disabled'
346 ],
347 [ 'xff' => '1.2.3.4, 50.2.1.1, 2001:4860:4001:802::1003, 2.3.4.5',
348 'count' => 2,
349 'result' => 'Range6 Hardblock'
350 ],
351 ];
352 }
353
354 /**
355 * @dataProvider providerXff
356 * @covers Block::getBlocksForIPList
357 * @covers Block::chooseBlock
358 */
359 public function testBlocksOnXff( $xff, $exCount, $exResult ) {
360 $user = $this->getUserForBlocking();
361 $this->addBlockForUser( $user );
362
363 $list = array_map( 'trim', explode( ',', $xff ) );
364 $xffblocks = Block::getBlocksForIPList( $list, true );
365 $this->assertEquals( $exCount, count( $xffblocks ), 'Number of blocks for ' . $xff );
366 $block = Block::chooseBlock( $xffblocks, $list );
367 $this->assertEquals( $exResult, $block->mReason, 'Correct block type for XFF header ' . $xff );
368 }
369
370 /**
371 * @covers Block::__construct
372 */
373 public function testDeprecatedConstructor() {
374 $this->hideDeprecated( 'Block::__construct with multiple arguments' );
375 $username = 'UnthinkablySecretRandomUsername';
376 $reason = 'being irrational';
377
378 # Set up the target
379 $u = User::newFromName( $username );
380 if ( $u->getId() == 0 ) {
381 $u->addToDatabase();
382 TestUser::setPasswordForUser( $u, 'TotallyObvious' );
383 }
384 unset( $u );
385
386 # Make sure the user isn't blocked
387 $this->assertNull(
388 Block::newFromTarget( $username ),
389 "$username should not be blocked"
390 );
391
392 # Perform the block
393 $block = new Block(
394 /* address */ $username,
395 /* user */ 0,
396 /* by */ 0,
397 /* reason */ $reason,
398 /* timestamp */ 0,
399 /* auto */ false,
400 /* expiry */ 0
401 );
402 $block->insert();
403
404 # Check target
405 $this->assertEquals(
406 $block->getTarget()->getName(),
407 $username,
408 "Target should be set properly"
409 );
410
411 # Check supplied parameter
412 $this->assertEquals(
413 $block->mReason,
414 $reason,
415 "Reason should be non-default"
416 );
417
418 # Check default parameter
419 $this->assertFalse(
420 (bool)$block->prevents( 'createaccount' ),
421 "Account creation should not be blocked by default"
422 );
423 }
424
425 /**
426 * @covers Block::getSystemBlockType
427 * @covers Block::insert
428 * @covers Block::doAutoblock
429 */
430 public function testSystemBlocks() {
431 $user = $this->getUserForBlocking();
432 $this->addBlockForUser( $user );
433
434 $blockOptions = [
435 'address' => $user->getName(),
436 'reason' => 'test system block',
437 'timestamp' => wfTimestampNow(),
438 'expiry' => $this->db->getInfinity(),
439 'byText' => 'MediaWiki default',
440 'systemBlock' => 'test',
441 'enableAutoblock' => true,
442 ];
443 $block = new Block( $blockOptions );
444
445 $this->assertSame( 'test', $block->getSystemBlockType() );
446
447 try {
448 $block->insert();
449 $this->fail( 'Expected exception not thrown' );
450 } catch ( MWException $ex ) {
451 $this->assertSame( 'Cannot insert a system block into the database', $ex->getMessage() );
452 }
453
454 try {
455 $block->doAutoblock( '192.0.2.2' );
456 $this->fail( 'Expected exception not thrown' );
457 } catch ( MWException $ex ) {
458 $this->assertSame( 'Cannot autoblock from a system block', $ex->getMessage() );
459 }
460 }
461
462 }