Merge "Properly detect if CACHE_ACCEL is available in the installer"
[lhc/web/wiklou.git] / tests / phpunit / includes / api / ApiMainTest.php
1 <?php
2
3 use Wikimedia\TestingAccessWrapper;
4
5 /**
6 * @group API
7 * @group Database
8 * @group medium
9 *
10 * @covers ApiMain
11 */
12 class ApiMainTest extends ApiTestCase {
13
14 /**
15 * Test that the API will accept a FauxRequest and execute.
16 */
17 public function testApi() {
18 $api = new ApiMain(
19 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
20 );
21 $api->execute();
22 $data = $api->getResult()->getResultData();
23 $this->assertInternalType( 'array', $data );
24 $this->assertArrayHasKey( 'query', $data );
25 }
26
27 public static function provideAssert() {
28 return [
29 [ false, [], 'user', 'assertuserfailed' ],
30 [ true, [], 'user', false ],
31 [ true, [], 'bot', 'assertbotfailed' ],
32 [ true, [ 'bot' ], 'user', false ],
33 [ true, [ 'bot' ], 'bot', false ],
34 ];
35 }
36
37 /**
38 * Tests the assert={user|bot} functionality
39 *
40 * @covers ApiMain::checkAsserts
41 * @dataProvider provideAssert
42 * @param bool $registered
43 * @param array $rights
44 * @param string $assert
45 * @param string|bool $error False if no error expected
46 */
47 public function testAssert( $registered, $rights, $assert, $error ) {
48 $user = new User();
49 if ( $registered ) {
50 $user->setId( 1 );
51 }
52 $user->mRights = $rights;
53 try {
54 $this->doApiRequest( [
55 'action' => 'query',
56 'assert' => $assert,
57 ], null, null, $user );
58 $this->assertFalse( $error ); // That no error was expected
59 } catch ( ApiUsageException $e ) {
60 $this->assertTrue( self::apiExceptionHasCode( $e, $error ) );
61 }
62 }
63
64 /**
65 * Tests the assertuser= functionality
66 *
67 * @covers ApiMain::checkAsserts
68 */
69 public function testAssertUser() {
70 $user = $this->getTestUser()->getUser();
71 $this->doApiRequest( [
72 'action' => 'query',
73 'assertuser' => $user->getName(),
74 ], null, null, $user );
75
76 try {
77 $this->doApiRequest( [
78 'action' => 'query',
79 'assertuser' => $user->getName() . 'X',
80 ], null, null, $user );
81 $this->fail( 'Expected exception not thrown' );
82 } catch ( ApiUsageException $e ) {
83 $this->assertTrue( self::apiExceptionHasCode( $e, 'assertnameduserfailed' ) );
84 }
85 }
86
87 /**
88 * Test if all classes in the main module manager exists
89 */
90 public function testClassNamesInModuleManager() {
91 $api = new ApiMain(
92 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
93 );
94 $modules = $api->getModuleManager()->getNamesWithClasses();
95
96 foreach ( $modules as $name => $class ) {
97 $this->assertTrue(
98 class_exists( $class ),
99 'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
100 );
101 }
102 }
103
104 /**
105 * Test HTTP precondition headers
106 *
107 * @covers ApiMain::checkConditionalRequestHeaders
108 * @dataProvider provideCheckConditionalRequestHeaders
109 * @param array $headers HTTP headers
110 * @param array $conditions Return data for ApiBase::getConditionalRequestData
111 * @param int $status Expected response status
112 * @param bool $post Request is a POST
113 */
114 public function testCheckConditionalRequestHeaders(
115 $headers, $conditions, $status, $post = false
116 ) {
117 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
118 $request->setHeaders( $headers );
119 $request->response()->statusHeader( 200 ); // Why doesn't it default?
120
121 $context = $this->apiContext->newTestContext( $request, null );
122 $api = new ApiMain( $context );
123 $priv = TestingAccessWrapper::newFromObject( $api );
124 $priv->mInternalMode = false;
125
126 $module = $this->getMockBuilder( 'ApiBase' )
127 ->setConstructorArgs( [ $api, 'mock' ] )
128 ->setMethods( [ 'getConditionalRequestData' ] )
129 ->getMockForAbstractClass();
130 $module->expects( $this->any() )
131 ->method( 'getConditionalRequestData' )
132 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
133 return isset( $conditions[$condition] ) ? $conditions[$condition] : null;
134 } ) );
135
136 $ret = $priv->checkConditionalRequestHeaders( $module );
137
138 $this->assertSame( $status, $request->response()->getStatusCode() );
139 $this->assertSame( $status === 200, $ret );
140 }
141
142 public static function provideCheckConditionalRequestHeaders() {
143 $now = time();
144
145 return [
146 // Non-existing from module is ignored
147 [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
148 [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
149
150 // No headers
151 [
152 [],
153 [
154 'etag' => '""',
155 'last-modified' => '20150815000000',
156 ],
157 200
158 ],
159
160 // Basic If-None-Match
161 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
162 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
163 [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
164 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
165 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
166
167 // Pointless, but supported
168 [ [ 'If-None-Match' => '*' ], [], 304 ],
169
170 // Basic If-Modified-Since
171 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
172 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
173 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
174 [ 'last-modified' => wfTimestamp( TS_MW, $now ) ], 304 ],
175 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
176 [ 'last-modified' => wfTimestamp( TS_MW, $now + 1 ) ], 200 ],
177
178 // If-Modified-Since ignored when If-None-Match is given too
179 [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
180 [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
181 [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
182 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
183
184 // Ignored for POST
185 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200, true ],
186 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
187 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200, true ],
188
189 // Other date formats allowed by the RFC
190 [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
191 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
192 [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
193 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
194
195 // Old browser extension to HTTP/1.0
196 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) . '; length=123' ],
197 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
198
199 // Invalid date formats should be ignored
200 [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
201 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
202 ];
203 }
204
205 /**
206 * Test conditional headers output
207 * @dataProvider provideConditionalRequestHeadersOutput
208 * @param array $conditions Return data for ApiBase::getConditionalRequestData
209 * @param array $headers Expected output headers
210 * @param bool $isError $isError flag
211 * @param bool $post Request is a POST
212 */
213 public function testConditionalRequestHeadersOutput(
214 $conditions, $headers, $isError = false, $post = false
215 ) {
216 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
217 $response = $request->response();
218
219 $api = new ApiMain( $request );
220 $priv = TestingAccessWrapper::newFromObject( $api );
221 $priv->mInternalMode = false;
222
223 $module = $this->getMockBuilder( 'ApiBase' )
224 ->setConstructorArgs( [ $api, 'mock' ] )
225 ->setMethods( [ 'getConditionalRequestData' ] )
226 ->getMockForAbstractClass();
227 $module->expects( $this->any() )
228 ->method( 'getConditionalRequestData' )
229 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
230 return isset( $conditions[$condition] ) ? $conditions[$condition] : null;
231 } ) );
232 $priv->mModule = $module;
233
234 $priv->sendCacheHeaders( $isError );
235
236 foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
237 $this->assertEquals(
238 isset( $headers[$header] ) ? $headers[$header] : null,
239 $response->getHeader( $header ),
240 $header
241 );
242 }
243 }
244
245 public static function provideConditionalRequestHeadersOutput() {
246 return [
247 [
248 [],
249 []
250 ],
251 [
252 [ 'etag' => '"foo"' ],
253 [ 'ETag' => '"foo"' ]
254 ],
255 [
256 [ 'last-modified' => '20150818000102' ],
257 [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
258 ],
259 [
260 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
261 [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
262 ],
263 [
264 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
265 [],
266 true,
267 ],
268 [
269 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
270 [],
271 false,
272 true,
273 ],
274 ];
275 }
276
277 /**
278 * @covers ApiMain::lacksSameOriginSecurity
279 */
280 public function testLacksSameOriginSecurity() {
281 // Basic test
282 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
283 $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
284
285 // JSONp
286 $main = new ApiMain(
287 new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
288 );
289 $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
290
291 // Header
292 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
293 $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
294 $main = new ApiMain( $request );
295 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
296
297 // Hook
298 $this->mergeMwGlobalArrayValue( 'wgHooks', [
299 'RequestHasSameOriginSecurity' => [ function () {
300 return false;
301 } ]
302 ] );
303 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
304 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
305 }
306
307 /**
308 * Test proper creation of the ApiErrorFormatter
309 * @covers ApiMain::__construct
310 * @dataProvider provideApiErrorFormatterCreation
311 * @param array $request Request parameters
312 * @param array $expect Expected data
313 * - uselang: ApiMain language
314 * - class: ApiErrorFormatter class
315 * - lang: ApiErrorFormatter language
316 * - format: ApiErrorFormatter format
317 * - usedb: ApiErrorFormatter use-database flag
318 */
319 public function testApiErrorFormatterCreation( array $request, array $expect ) {
320 $context = new RequestContext();
321 $context->setRequest( new FauxRequest( $request ) );
322 $context->setLanguage( 'ru' );
323
324 $main = new ApiMain( $context );
325 $formatter = $main->getErrorFormatter();
326 $wrappedFormatter = TestingAccessWrapper::newFromObject( $formatter );
327
328 $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
329 $this->assertInstanceOf( $expect['class'], $formatter );
330 $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
331 $this->assertSame( $expect['format'], $wrappedFormatter->format );
332 $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB );
333 }
334
335 public static function provideApiErrorFormatterCreation() {
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' => 'en',
386 'class' => ApiErrorFormatter::class,
387 'lang' => 'en',
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' => 'en',
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 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(
491 $this->createMock( 'IDatabase' ),
492 'error', 1234, 'SELECT 1', __METHOD__ );
493 $dbtrace = wfMessage( 'api-exception-trace',
494 get_class( $dbex ),
495 $dbex->getFile(),
496 $dbex->getLine(),
497 MWExceptionHandler::getRedactedTraceAsString( $dbex )
498 )->inLanguage( 'en' )->useDatabase( false )->text();
499
500 $apiEx1 = new ApiUsageException( null,
501 StatusValue::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
502 TestingAccessWrapper::newFromObject( $apiEx1 )->modulePath = 'foo+bar';
503 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
504 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
505 $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
506
507 return [
508 [
509 $ex,
510 [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
511 [
512 'warnings' => [
513 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
514 ],
515 'errors' => [
516 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
517 [
518 'code' => 'internal_api_error_InvalidArgumentException',
519 'text' => "[$reqId] Exception caught: Random exception",
520 ]
521 ],
522 'trace' => $trace,
523 'servedby' => wfHostname(),
524 ]
525 ],
526 [
527 $dbex,
528 [ 'existing-error', 'internal_api_error_DBQueryError' ],
529 [
530 'warnings' => [
531 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
532 ],
533 'errors' => [
534 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
535 [
536 'code' => 'internal_api_error_DBQueryError',
537 'text' => "[$reqId] Database query error.",
538 ]
539 ],
540 'trace' => $dbtrace,
541 'servedby' => wfHostname(),
542 ]
543 ],
544 [
545 new UsageException( 'Usage exception!', 'ue', 0, [ 'foo' => 'bar' ] ),
546 [ 'existing-error', 'ue' ],
547 [
548 'warnings' => [
549 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
550 ],
551 'errors' => [
552 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
553 [ 'code' => 'ue', 'text' => "Usage exception!", 'data' => [ 'foo' => 'bar' ] ]
554 ],
555 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
556 "list at &lt;https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce&gt; " .
557 "for notice of API deprecations and breaking changes.",
558 'servedby' => wfHostname(),
559 ]
560 ],
561 [
562 $apiEx1,
563 [ 'existing-error', 'sv-error1', 'sv-error2' ],
564 [
565 'warnings' => [
566 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
567 [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
568 [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
569 ],
570 'errors' => [
571 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
572 [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
573 [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
574 ],
575 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
576 "list at &lt;https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce&gt; " .
577 "for notice of API deprecations and breaking changes.",
578 'servedby' => wfHostname(),
579 ]
580 ],
581 ];
582 }
583 }