Merge "Don't create user in AuthManagerTest dataProvider"
[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 global $wgContLang;
335
336 return [
337 'Default (BC)' => [ [], [
338 'uselang' => 'ru',
339 'class' => ApiErrorFormatter_BackCompat::class,
340 'lang' => 'en',
341 'format' => 'none',
342 'usedb' => false,
343 ] ],
344 'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
345 'uselang' => 'ru',
346 'class' => ApiErrorFormatter_BackCompat::class,
347 'lang' => 'en',
348 'format' => 'none',
349 'usedb' => false,
350 ] ],
351 'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
352 'uselang' => 'ru',
353 'class' => ApiErrorFormatter_BackCompat::class,
354 'lang' => 'en',
355 'format' => 'none',
356 'usedb' => false,
357 ] ],
358 'Basic' => [ [ 'errorformat' => 'wikitext' ], [
359 'uselang' => 'ru',
360 'class' => ApiErrorFormatter::class,
361 'lang' => 'ru',
362 'format' => 'wikitext',
363 'usedb' => false,
364 ] ],
365 'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
366 'uselang' => 'fr',
367 'class' => ApiErrorFormatter::class,
368 'lang' => 'fr',
369 'format' => 'plaintext',
370 'usedb' => false,
371 ] ],
372 'Explicitly follows uselang' => [
373 [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
374 [
375 'uselang' => 'fr',
376 'class' => ApiErrorFormatter::class,
377 'lang' => 'fr',
378 'format' => 'plaintext',
379 'usedb' => false,
380 ]
381 ],
382 'uselang=content' => [
383 [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
384 [
385 'uselang' => $wgContLang->getCode(),
386 'class' => ApiErrorFormatter::class,
387 'lang' => $wgContLang->getCode(),
388 'format' => 'plaintext',
389 'usedb' => false,
390 ]
391 ],
392 'errorlang=content' => [
393 [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
394 [
395 'uselang' => 'ru',
396 'class' => ApiErrorFormatter::class,
397 'lang' => $wgContLang->getCode(),
398 'format' => 'plaintext',
399 'usedb' => false,
400 ]
401 ],
402 'Explicit parameters' => [
403 [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
404 [
405 'uselang' => 'ru',
406 'class' => ApiErrorFormatter::class,
407 'lang' => 'de',
408 'format' => 'html',
409 'usedb' => true,
410 ]
411 ],
412 'Explicit parameters override uselang' => [
413 [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
414 [
415 'uselang' => 'fr',
416 'class' => ApiErrorFormatter::class,
417 'lang' => 'de',
418 'format' => 'raw',
419 'usedb' => false,
420 ]
421 ],
422 'Bogus language doesn\'t explode' => [
423 [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
424 [
425 'uselang' => 'en',
426 'class' => ApiErrorFormatter::class,
427 'lang' => 'en',
428 'format' => 'none',
429 'usedb' => false,
430 ]
431 ],
432 'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
433 'uselang' => 'ru',
434 'class' => ApiErrorFormatter_BackCompat::class,
435 'lang' => 'en',
436 'format' => 'none',
437 'usedb' => false,
438 ] ],
439 ];
440 }
441
442 /**
443 * @covers ApiMain::errorMessagesFromException
444 * @covers ApiMain::substituteResultWithError
445 * @dataProvider provideExceptionErrors
446 * @param Exception $exception
447 * @param array $expectReturn
448 * @param array $expectResult
449 */
450 public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
451 $context = new RequestContext();
452 $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
453 $context->setLanguage( 'en' );
454 $context->setConfig( new MultiConfig( [
455 new HashConfig( [
456 'ShowHostnames' => true, 'ShowSQLErrors' => false,
457 'ShowExceptionDetails' => true, 'ShowDBErrorBacktrace' => true,
458 ] ),
459 $context->getConfig()
460 ] ) );
461
462 $main = new ApiMain( $context );
463 $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
464 $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
465
466 $ret = TestingAccessWrapper::newFromObject( $main )->substituteResultWithError( $error );
467 $this->assertSame( $expectReturn, $ret );
468
469 // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
470 // so let's try ->assertEquals().
471 $this->assertEquals(
472 $expectResult,
473 $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
474 );
475 }
476
477 // Not static so $this->getMock() can be used
478 public function provideExceptionErrors() {
479 $reqId = WebRequest::getRequestId();
480 $doclink = wfExpandUrl( wfScript( 'api' ) );
481
482 $ex = new InvalidArgumentException( 'Random exception' );
483 $trace = wfMessage( 'api-exception-trace',
484 get_class( $ex ),
485 $ex->getFile(),
486 $ex->getLine(),
487 MWExceptionHandler::getRedactedTraceAsString( $ex )
488 )->inLanguage( 'en' )->useDatabase( false )->text();
489
490 $dbex = new DBQueryError( $this->getMock( 'IDatabase' ), '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 }