Merge "phpunit: Avoid use of deprecated getMock for PHPUnit 5 compat"
[lhc/web/wiklou.git] / tests / phpunit / includes / api / ApiMainTest.php
1 <?php
2
3 /**
4 * @group API
5 * @group Database
6 * @group medium
7 *
8 * @covers ApiMain
9 */
10 class ApiMainTest extends ApiTestCase {
11
12 /**
13 * Test that the API will accept a FauxRequest and execute.
14 */
15 public function testApi() {
16 $api = new ApiMain(
17 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
18 );
19 $api->execute();
20 $data = $api->getResult()->getResultData();
21 $this->assertInternalType( 'array', $data );
22 $this->assertArrayHasKey( 'query', $data );
23 }
24
25 public static function provideAssert() {
26 return [
27 [ false, [], 'user', 'assertuserfailed' ],
28 [ true, [], 'user', false ],
29 [ true, [], 'bot', 'assertbotfailed' ],
30 [ true, [ 'bot' ], 'user', false ],
31 [ true, [ 'bot' ], 'bot', false ],
32 ];
33 }
34
35 /**
36 * Tests the assert={user|bot} functionality
37 *
38 * @covers ApiMain::checkAsserts
39 * @dataProvider provideAssert
40 * @param bool $registered
41 * @param array $rights
42 * @param string $assert
43 * @param string|bool $error False if no error expected
44 */
45 public function testAssert( $registered, $rights, $assert, $error ) {
46 $user = new User();
47 if ( $registered ) {
48 $user->setId( 1 );
49 }
50 $user->mRights = $rights;
51 try {
52 $this->doApiRequest( [
53 'action' => 'query',
54 'assert' => $assert,
55 ], null, null, $user );
56 $this->assertFalse( $error ); // That no error was expected
57 } catch ( ApiUsageException $e ) {
58 $this->assertTrue( self::apiExceptionHasCode( $e, $error ) );
59 }
60 }
61
62 /**
63 * Tests the assertuser= functionality
64 *
65 * @covers ApiMain::checkAsserts
66 */
67 public function testAssertUser() {
68 $user = $this->getTestUser()->getUser();
69 $this->doApiRequest( [
70 'action' => 'query',
71 'assertuser' => $user->getName(),
72 ], null, null, $user );
73
74 try {
75 $this->doApiRequest( [
76 'action' => 'query',
77 'assertuser' => $user->getName() . 'X',
78 ], null, null, $user );
79 $this->fail( 'Expected exception not thrown' );
80 } catch ( ApiUsageException $e ) {
81 $this->assertTrue( self::apiExceptionHasCode( $e, 'assertnameduserfailed' ) );
82 }
83 }
84
85 /**
86 * Test if all classes in the main module manager exists
87 */
88 public function testClassNamesInModuleManager() {
89 $api = new ApiMain(
90 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
91 );
92 $modules = $api->getModuleManager()->getNamesWithClasses();
93
94 foreach ( $modules as $name => $class ) {
95 $this->assertTrue(
96 class_exists( $class ),
97 'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
98 );
99 }
100 }
101
102 /**
103 * Test HTTP precondition headers
104 *
105 * @covers ApiMain::checkConditionalRequestHeaders
106 * @dataProvider provideCheckConditionalRequestHeaders
107 * @param array $headers HTTP headers
108 * @param array $conditions Return data for ApiBase::getConditionalRequestData
109 * @param int $status Expected response status
110 * @param bool $post Request is a POST
111 */
112 public function testCheckConditionalRequestHeaders(
113 $headers, $conditions, $status, $post = false
114 ) {
115 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
116 $request->setHeaders( $headers );
117 $request->response()->statusHeader( 200 ); // Why doesn't it default?
118
119 $context = $this->apiContext->newTestContext( $request, null );
120 $api = new ApiMain( $context );
121 $priv = TestingAccessWrapper::newFromObject( $api );
122 $priv->mInternalMode = false;
123
124 $module = $this->getMockBuilder( 'ApiBase' )
125 ->setConstructorArgs( [ $api, 'mock' ] )
126 ->setMethods( [ 'getConditionalRequestData' ] )
127 ->getMockForAbstractClass();
128 $module->expects( $this->any() )
129 ->method( 'getConditionalRequestData' )
130 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
131 return isset( $conditions[$condition] ) ? $conditions[$condition] : null;
132 } ) );
133
134 $ret = $priv->checkConditionalRequestHeaders( $module );
135
136 $this->assertSame( $status, $request->response()->getStatusCode() );
137 $this->assertSame( $status === 200, $ret );
138 }
139
140 public static function provideCheckConditionalRequestHeaders() {
141 $now = time();
142
143 return [
144 // Non-existing from module is ignored
145 [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
146 [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
147
148 // No headers
149 [
150 [],
151 [
152 'etag' => '""',
153 'last-modified' => '20150815000000',
154 ],
155 200
156 ],
157
158 // Basic If-None-Match
159 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
160 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
161 [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
162 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
163 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
164
165 // Pointless, but supported
166 [ [ 'If-None-Match' => '*' ], [], 304 ],
167
168 // Basic If-Modified-Since
169 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
170 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
171 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
172 [ 'last-modified' => wfTimestamp( TS_MW, $now ) ], 304 ],
173 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
174 [ 'last-modified' => wfTimestamp( TS_MW, $now + 1 ) ], 200 ],
175
176 // If-Modified-Since ignored when If-None-Match is given too
177 [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
178 [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
179 [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
180 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
181
182 // Ignored for POST
183 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200, true ],
184 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
185 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200, true ],
186
187 // Other date formats allowed by the RFC
188 [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
189 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
190 [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
191 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
192
193 // Old browser extension to HTTP/1.0
194 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) . '; length=123' ],
195 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
196
197 // Invalid date formats should be ignored
198 [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
199 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
200 ];
201 }
202
203 /**
204 * Test conditional headers output
205 * @dataProvider provideConditionalRequestHeadersOutput
206 * @param array $conditions Return data for ApiBase::getConditionalRequestData
207 * @param array $headers Expected output headers
208 * @param bool $isError $isError flag
209 * @param bool $post Request is a POST
210 */
211 public function testConditionalRequestHeadersOutput(
212 $conditions, $headers, $isError = false, $post = false
213 ) {
214 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
215 $response = $request->response();
216
217 $api = new ApiMain( $request );
218 $priv = TestingAccessWrapper::newFromObject( $api );
219 $priv->mInternalMode = false;
220
221 $module = $this->getMockBuilder( 'ApiBase' )
222 ->setConstructorArgs( [ $api, 'mock' ] )
223 ->setMethods( [ 'getConditionalRequestData' ] )
224 ->getMockForAbstractClass();
225 $module->expects( $this->any() )
226 ->method( 'getConditionalRequestData' )
227 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
228 return isset( $conditions[$condition] ) ? $conditions[$condition] : null;
229 } ) );
230 $priv->mModule = $module;
231
232 $priv->sendCacheHeaders( $isError );
233
234 foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
235 $this->assertEquals(
236 isset( $headers[$header] ) ? $headers[$header] : null,
237 $response->getHeader( $header ),
238 $header
239 );
240 }
241 }
242
243 public static function provideConditionalRequestHeadersOutput() {
244 return [
245 [
246 [],
247 []
248 ],
249 [
250 [ 'etag' => '"foo"' ],
251 [ 'ETag' => '"foo"' ]
252 ],
253 [
254 [ 'last-modified' => '20150818000102' ],
255 [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
256 ],
257 [
258 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
259 [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
260 ],
261 [
262 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
263 [],
264 true,
265 ],
266 [
267 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
268 [],
269 false,
270 true,
271 ],
272 ];
273 }
274
275 /**
276 * @covers ApiMain::lacksSameOriginSecurity
277 */
278 public function testLacksSameOriginSecurity() {
279 // Basic test
280 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
281 $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
282
283 // JSONp
284 $main = new ApiMain(
285 new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
286 );
287 $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
288
289 // Header
290 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
291 $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
292 $main = new ApiMain( $request );
293 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
294
295 // Hook
296 $this->mergeMwGlobalArrayValue( 'wgHooks', [
297 'RequestHasSameOriginSecurity' => [ function () {
298 return false;
299 } ]
300 ] );
301 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
302 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
303 }
304
305 /**
306 * Test proper creation of the ApiErrorFormatter
307 * @covers ApiMain::__construct
308 * @dataProvider provideApiErrorFormatterCreation
309 * @param array $request Request parameters
310 * @param array $expect Expected data
311 * - uselang: ApiMain language
312 * - class: ApiErrorFormatter class
313 * - lang: ApiErrorFormatter language
314 * - format: ApiErrorFormatter format
315 * - usedb: ApiErrorFormatter use-database flag
316 */
317 public function testApiErrorFormatterCreation( array $request, array $expect ) {
318 $context = new RequestContext();
319 $context->setRequest( new FauxRequest( $request ) );
320 $context->setLanguage( 'ru' );
321
322 $main = new ApiMain( $context );
323 $formatter = $main->getErrorFormatter();
324 $wrappedFormatter = TestingAccessWrapper::newFromObject( $formatter );
325
326 $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
327 $this->assertInstanceOf( $expect['class'], $formatter );
328 $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
329 $this->assertSame( $expect['format'], $wrappedFormatter->format );
330 $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB );
331 }
332
333 public static function provideApiErrorFormatterCreation() {
334 return [
335 'Default (BC)' => [ [], [
336 'uselang' => 'ru',
337 'class' => ApiErrorFormatter_BackCompat::class,
338 'lang' => 'en',
339 'format' => 'none',
340 'usedb' => false,
341 ] ],
342 'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
343 'uselang' => 'ru',
344 'class' => ApiErrorFormatter_BackCompat::class,
345 'lang' => 'en',
346 'format' => 'none',
347 'usedb' => false,
348 ] ],
349 'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
350 'uselang' => 'ru',
351 'class' => ApiErrorFormatter_BackCompat::class,
352 'lang' => 'en',
353 'format' => 'none',
354 'usedb' => false,
355 ] ],
356 'Basic' => [ [ 'errorformat' => 'wikitext' ], [
357 'uselang' => 'ru',
358 'class' => ApiErrorFormatter::class,
359 'lang' => 'ru',
360 'format' => 'wikitext',
361 'usedb' => false,
362 ] ],
363 'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
364 'uselang' => 'fr',
365 'class' => ApiErrorFormatter::class,
366 'lang' => 'fr',
367 'format' => 'plaintext',
368 'usedb' => false,
369 ] ],
370 'Explicitly follows uselang' => [
371 [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
372 [
373 'uselang' => 'fr',
374 'class' => ApiErrorFormatter::class,
375 'lang' => 'fr',
376 'format' => 'plaintext',
377 'usedb' => false,
378 ]
379 ],
380 'uselang=content' => [
381 [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
382 [
383 'uselang' => 'en',
384 'class' => ApiErrorFormatter::class,
385 'lang' => 'en',
386 'format' => 'plaintext',
387 'usedb' => false,
388 ]
389 ],
390 'errorlang=content' => [
391 [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
392 [
393 'uselang' => 'ru',
394 'class' => ApiErrorFormatter::class,
395 'lang' => 'en',
396 'format' => 'plaintext',
397 'usedb' => false,
398 ]
399 ],
400 'Explicit parameters' => [
401 [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
402 [
403 'uselang' => 'ru',
404 'class' => ApiErrorFormatter::class,
405 'lang' => 'de',
406 'format' => 'html',
407 'usedb' => true,
408 ]
409 ],
410 'Explicit parameters override uselang' => [
411 [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
412 [
413 'uselang' => 'fr',
414 'class' => ApiErrorFormatter::class,
415 'lang' => 'de',
416 'format' => 'raw',
417 'usedb' => false,
418 ]
419 ],
420 'Bogus language doesn\'t explode' => [
421 [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
422 [
423 'uselang' => 'en',
424 'class' => ApiErrorFormatter::class,
425 'lang' => 'en',
426 'format' => 'none',
427 'usedb' => false,
428 ]
429 ],
430 'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
431 'uselang' => 'ru',
432 'class' => ApiErrorFormatter_BackCompat::class,
433 'lang' => 'en',
434 'format' => 'none',
435 'usedb' => false,
436 ] ],
437 ];
438 }
439
440 /**
441 * @covers ApiMain::errorMessagesFromException
442 * @covers ApiMain::substituteResultWithError
443 * @dataProvider provideExceptionErrors
444 * @param Exception $exception
445 * @param array $expectReturn
446 * @param array $expectResult
447 */
448 public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
449 $context = new RequestContext();
450 $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
451 $context->setLanguage( 'en' );
452 $context->setConfig( new MultiConfig( [
453 new HashConfig( [
454 'ShowHostnames' => true, 'ShowSQLErrors' => false,
455 'ShowExceptionDetails' => true, 'ShowDBErrorBacktrace' => true,
456 ] ),
457 $context->getConfig()
458 ] ) );
459
460 $main = new ApiMain( $context );
461 $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
462 $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
463
464 $ret = TestingAccessWrapper::newFromObject( $main )->substituteResultWithError( $error );
465 $this->assertSame( $expectReturn, $ret );
466
467 // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
468 // so let's try ->assertEquals().
469 $this->assertEquals(
470 $expectResult,
471 $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
472 );
473 }
474
475 // Not static so $this can be used
476 public function provideExceptionErrors() {
477 $reqId = WebRequest::getRequestId();
478 $doclink = wfExpandUrl( wfScript( 'api' ) );
479
480 $ex = new InvalidArgumentException( 'Random exception' );
481 $trace = wfMessage( 'api-exception-trace',
482 get_class( $ex ),
483 $ex->getFile(),
484 $ex->getLine(),
485 MWExceptionHandler::getRedactedTraceAsString( $ex )
486 )->inLanguage( 'en' )->useDatabase( false )->text();
487
488 $dbex = new DBQueryError(
489 $this->createMock( 'IDatabase' ),
490 'error', 1234, 'SELECT 1', __METHOD__ );
491 $dbtrace = wfMessage( 'api-exception-trace',
492 get_class( $dbex ),
493 $dbex->getFile(),
494 $dbex->getLine(),
495 MWExceptionHandler::getRedactedTraceAsString( $dbex )
496 )->inLanguage( 'en' )->useDatabase( false )->text();
497
498 $apiEx1 = new ApiUsageException( null,
499 StatusValue::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
500 TestingAccessWrapper::newFromObject( $apiEx1 )->modulePath = 'foo+bar';
501 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
502 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
503 $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
504
505 return [
506 [
507 $ex,
508 [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
509 [
510 'warnings' => [
511 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
512 ],
513 'errors' => [
514 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
515 [
516 'code' => 'internal_api_error_InvalidArgumentException',
517 'text' => "[$reqId] Exception caught: Random exception",
518 ]
519 ],
520 'trace' => $trace,
521 'servedby' => wfHostname(),
522 ]
523 ],
524 [
525 $dbex,
526 [ 'existing-error', 'internal_api_error_DBQueryError' ],
527 [
528 'warnings' => [
529 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
530 ],
531 'errors' => [
532 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
533 [
534 'code' => 'internal_api_error_DBQueryError',
535 'text' => "[$reqId] Database query error.",
536 ]
537 ],
538 'trace' => $dbtrace,
539 'servedby' => wfHostname(),
540 ]
541 ],
542 [
543 new UsageException( 'Usage exception!', 'ue', 0, [ 'foo' => 'bar' ] ),
544 [ 'existing-error', 'ue' ],
545 [
546 'warnings' => [
547 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
548 ],
549 'errors' => [
550 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
551 [ 'code' => 'ue', 'text' => "Usage exception!", 'data' => [ 'foo' => 'bar' ] ]
552 ],
553 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
554 "list at &lt;https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce&gt; " .
555 "for notice of API deprecations and breaking changes.",
556 'servedby' => wfHostname(),
557 ]
558 ],
559 [
560 $apiEx1,
561 [ 'existing-error', 'sv-error1', 'sv-error2' ],
562 [
563 'warnings' => [
564 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
565 [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
566 [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
567 ],
568 'errors' => [
569 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
570 [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
571 [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
572 ],
573 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
574 "list at &lt;https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce&gt; " .
575 "for notice of API deprecations and breaking changes.",
576 'servedby' => wfHostname(),
577 ]
578 ],
579 ];
580 }
581 }