aboutsummaryrefslogtreecommitdiffstats
path: root/tests/phpunit/unit/includes/api/ApiUnblockTest.php
blob: e78240f08763b5edf9b15ab795ad993ba4518224 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
<?php

namespace MediaWiki\Tests\Unit\Api;

use ApiMain;
use ApiResult;
use ApiUnblock;
use Exception;
use MediaWiki\Block\BlockPermissionChecker;
use MediaWiki\Block\BlockPermissionCheckerFactory;
use MediaWiki\Block\DatabaseBlock;
use MediaWiki\Block\UnblockUser;
use MediaWiki\Block\UnblockUserFactory;
use MediaWikiUnitTestCase;
use RequestContext;
use Status;
use User;
use UserCache;

/**
 * @covers ApiUnblock
 *
 * @author DannyS712
 */
class ApiUnblockTest extends MediaWikiUnitTestCase {

	private function getConstructorArgs() {
		// So these don't need to be created each time
		$apiMain = $this->createMock( ApiMain::class );

		// ApiBase::__construct sets its context from ApiMain
		$requestContext = new RequestContext();
		$apiMain->method( 'getContext' )
			->willReturn( $requestContext );

		// Needed for $this->getUser()
		$performer = $this->createMock( User::class );
		$requestContext->setUser( $performer );

		$action = 'unblock';
		$blockPermissionCheckerFactory = $this->createMock( BlockPermissionCheckerFactory::class );
		$unblockUserFactory = $this->createMock( UnblockUserFactory::class );
		$userCache = $this->createMock( UserCache::class );

		// Expose requestContext and user so that they can be further modified in the test
		$returnVals = [
			'apiMain' => $apiMain,
			'action' => 'unblock',
			'blockPermissionCheckerFactory' => $blockPermissionCheckerFactory,
			'unblockUserFactory' => $unblockUserFactory,
			'userCache' => $userCache,
			'requestContext' => $requestContext,
			'performer' => $performer,
		];
		return $returnVals;
	}

	private function getMockApiUnblock( $args, $methods, $requestParams ) {
		// Avoid code duplication. Create the mock object with the constructor args
		// in $args, the $methods methods mocked, and with ::extractRequestParams
		// returning the $requestParams
		$apiUnblock = $this->getMockBuilder( ApiUnblock::class )
			->onlyMethods( $methods )
			->setConstructorArgs( [
				$args['apiMain'],
				$args['action'],
				$args['blockPermissionCheckerFactory'],
				$args['unblockUserFactory'],
				$args['userCache']
			] )
			->getMock();

		$apiUnblock->method( 'extractRequestParams' )
			->willReturn( $requestParams );

		return $apiUnblock;
	}

	private function getBlockPermissionCheckerFactory( $target, $performer, $status ) {
		// Factory returns a checker that returns the result
		$blockPermissionChecker = $this->createMock( BlockPermissionChecker::class );
		$blockPermissionChecker->expects( $this->once() )
			->method( 'checkBlockPermissions' )
			->willReturn( $status );

		$blockPermissionCheckerFactory = $this->createMock( BlockPermissionCheckerFactory::class );
		$blockPermissionCheckerFactory->expects( $this->once() )
			->method( 'newBlockPermissionChecker' )
			->with(
				$this->equalTo( $target ),
				$this->equalTo( $performer )
			)
			->willReturn( $blockPermissionChecker );

		return $blockPermissionCheckerFactory;
	}

	private function getUnblockUserFactory( $target, $performer, $reason, $tags, $status ) {
		// Factory returns an UnblockUser that returns the result
		$unblockUser = $this->createMock( UnblockUser::class );
		$unblockUser->expects( $this->once() )
			->method( 'unblock' )
			->willReturn( $status );

		$unblockUserFactory = $this->createMock( UnblockUserFactory::class );
		$unblockUserFactory->expects( $this->once() )
			->method( 'newUnblockUser' )
			->with(
				$this->equalTo( $target ),
				$this->equalTo( $performer ),
				$this->equalTo( $reason ),
				$this->equalTo( $tags )
			)
			->willReturn( $unblockUser );

		return $unblockUserFactory;
	}

	public function testConstruct() {
		$args = $this->getConstructorArgs();

		$apiUnblock = new ApiUnblock(
			$args['apiMain'],
			$args['action'],
			$args['blockPermissionCheckerFactory'],
			$args['unblockUserFactory'],
			$args['userCache']
		);
		// Ensure everything was created right
		$this->assertInstanceOf(
			ApiUnblock::class,
			$apiUnblock
		);
	}

	public function testDieOnlyOneParameter() {
		// Test that `$this->requireOnlyOneParameter( $params, 'id', 'user', 'userid' );`
		// is properly called; since the actual internals of that are complicated,
		// mock it
		$args = $this->getConstructorArgs();

		$requestParams = [ 'actual contents are not used in this test' ];
		$apiUnblock = $this->getMockApiUnblock(
			$args,
			[ 'extractRequestParams', 'requireOnlyOneParameter' ],
			$requestParams
		);

		$testException = new Exception( 'Error should be thrown in requireOnlyOneParameter' );
		$apiUnblock->method( 'requireOnlyOneParameter' )
			->with(
				$this->equalTo( $requestParams ),
				$this->equalTo( 'id' ),
				$this->equalTo( 'user' ),
				$this->equalTo( 'userid' )
			)
			->will( $this->throwException( $testException ) );

		$this->expectException( Exception::class );
		$this->expectExceptionMessage( 'Error should be thrown in requireOnlyOneParameter' );
		$apiUnblock->execute();
	}

	public function testPermissionDenied() {
		// Test that if the permission manager call fails, dieWithError is called
		// Since the actual internals of that are complicated, mock it
		$args = $this->getConstructorArgs();

		$args['performer']->expects( $this->once() )
			->method( 'isAllowed' )
			->with(
				$this->equalTo( 'block' )
			)
			->willReturn( false );

		$requestParams = [ 'actual contents are not used in this test' ];
		$apiUnblock = $this->getMockApiUnblock(
			$args,
			[ 'extractRequestParams', 'requireOnlyOneParameter', 'dieWithError' ],
			$requestParams
		);

		// No need to do anything with requireOnlyOneParameter

		$testException = new Exception( 'Error should be thrown in dieWithError' );
		$apiUnblock->method( 'dieWithError' )
			->with(
				$this->equalTo( 'apierror-permissiondenied-unblock' ),
				$this->equalTo( 'permissiondenied' )
			)
			->will( $this->throwException( $testException ) );

		$this->expectException( Exception::class );
		$this->expectExceptionMessage( 'Error should be thrown in dieWithError' );
		$apiUnblock->execute();
	}

	public function testNoSuchUserId() {
		// If $params['userid'] is set and the usercache call returns false, there is an error
		$args = $this->getConstructorArgs();

		$args['performer']->method( 'isAllowed' )->willReturn( true );

		$args['userCache']->expects( $this->once() )
			->method( 'getProp' )
			->with(
				$this->equalTo( 'userIdGoesHere' ),
				$this->equalTo( 'name' )
			)
			->willReturn( false );

		$requestParams = [ 'userid' => 'userIdGoesHere' ];
		$apiUnblock = $this->getMockApiUnblock(
			$args,
			[ 'extractRequestParams', 'requireOnlyOneParameter', 'dieWithError' ],
			$requestParams
		);

		// No need to do anything with requireOnlyOneParameter

		$testException = new Exception( 'Error should be thrown in dieWithError' );
		$apiUnblock->method( 'dieWithError' )
			->with(
				$this->equalTo( [ 'apierror-nosuchuserid', 'userIdGoesHere' ] ),
				$this->equalTo( 'nosuchuserid' )
			)
			->will( $this->throwException( $testException ) );

		$this->expectException( Exception::class );
		$this->expectExceptionMessage( 'Error should be thrown in dieWithError' );
		$apiUnblock->execute();
	}

	public function testUnblockBadStatus() {
		// For now, not going to test the BlockPermissionChecker failing, since
		// that requires supplying everything needed for the $this->getBlockDetails()
		// call (method is in a trait, so cannot easily be overridden). Additionally,
		// the trait uses `wfTimestamp` and calls `ApiResult::formatExpiry`, which uses
		// wfGetDB, wfIsInfinity, and wfTimestamp, so it may not be possible to test that part
		// Next potential failure is the actual unblock call failing
		$args = $this->getConstructorArgs();

		$args['performer']->method( 'isAllowed' )->willReturn( true );

		// Return true
		$args['blockPermissionCheckerFactory'] = $this->getBlockPermissionCheckerFactory(
			'userNameOfTargetFromCache',
			$args['performer'],
			true
		);

		// Also includes the test of the codepath where UserCache is used and works
		$args['userCache']->expects( $this->once() )
			->method( 'getProp' )
			->with(
				$this->equalTo( 'userIdGoesHere' ),
				$this->equalTo( 'name' )
			)
			->willReturn( 'userNameOfTargetFromCache' );

		$badStatus = Status::newFatal( 'bad status' );
		$args['unblockUserFactory'] = $this->getUnblockUserFactory(
			'userNameOfTargetFromCache',
			$args['performer'],
			'reasonGoesHere',
			[ 'tag 1' ],
			$badStatus
		);

		$requestParams = [
			'userid' => 'userIdGoesHere',
			'id' => null,
			'reason' => 'reasonGoesHere',
			'tags' => [ 'tag 1' ],
		];
		$apiUnblock = $this->getMockApiUnblock(
			$args,
			[ 'extractRequestParams', 'requireOnlyOneParameter', 'dieStatus' ],
			$requestParams
		);

		// No need to do anything with requireOnlyOneParameter

		$testException = new Exception( 'Error should be thrown in dieStatus' );
		$apiUnblock->method( 'dieStatus' )
			->with( $this->equalTo( $badStatus ) )
			->will( $this->throwException( $testException ) );

		$this->expectException( Exception::class );
		$this->expectExceptionMessage( 'Error should be thrown in dieStatus' );
		$apiUnblock->execute();
	}

	public function testSuccessfulUnblock() {
		// Everything works
		$args = $this->getConstructorArgs();

		// ApiBase::getResult just calls ApiMain::getResult, so we can mock it there
		$apiResult = $this->createMock( ApiResult::class );
		$apiResult->expects( $this->once() )
			->method( 'addValue' )
			->with(
				$this->equalTo( null ),
				$this->equalTo( $args['action'] ),
				$this->equalTo( [
					'id' => 678, // block id
					'user' => 'targetNameGoesHere', // target name
					'userid' => 123, // target user id
					'reason' => 'reasonGoesHere', // reason in $requestParams
				] )
			)
			->willReturn( true );
		$args['apiMain']->method( 'getResult' )->willReturn( $apiResult );

		$args['performer']->method( 'isAllowed' )->willReturn( true );
		$args['blockPermissionCheckerFactory'] = $this->getBlockPermissionCheckerFactory(
			'targetNameGoesHere',
			$args['performer'],
			true
		);

		$blockTarget = $this->createMock( User::class );
		$blockTarget->method( 'getName' )->willReturn( 'targetNameGoesHere' );
		$blockTarget->method( 'getId' )->willReturn( 123 );

		$databaseBlock = $this->createMock( DatabaseBlock::class );
		$databaseBlock->method( 'getType' )->willReturn( DatabaseBlock::TYPE_USER );
		$databaseBlock->method( 'getTarget' )->willReturn( $blockTarget );
		$databaseBlock->method( 'getId' )->willReturn( 678 );

		$goodStatus = Status::newGood( $databaseBlock );
		$args['unblockUserFactory'] = $this->getUnblockUserFactory(
			'targetNameGoesHere',
			$args['performer'],
			'reasonGoesHere',
			[ 'tag 2' ],
			$goodStatus
		);

		$requestParams = [
			'user' => 'targetNameGoesHere',
			'userid' => null,
			'id' => null,
			'reason' => 'reasonGoesHere',
			'tags' => [ 'tag 2' ],
		];

		$apiUnblock = $this->getMockApiUnblock(
			$args,
			[ 'extractRequestParams', 'requireOnlyOneParameter' ],
			$requestParams
		);

		// No need to do anything with requireOnlyOneParameter
		$apiUnblock->execute();

		// Make sure we got to the end
		$this->addToAssertionCount( 1 );
	}

}