Added release notes for 'ContentHandler::runLegacyHooks' removal
[mediawiki.git] / tests / phpunit / includes / api / ApiMainTest.php
blob71dafceb5ae7777eedddf18a0905bc9918a9f4ec
1 <?php
3 /**
4 * @group API
5 * @group medium
7 * @covers ApiMain
8 */
9 class ApiMainTest extends ApiTestCase {
11 /**
12 * Test that the API will accept a FauxRequest and execute.
14 public function testApi() {
15 $api = new ApiMain(
16 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
18 $api->execute();
19 $data = $api->getResult()->getResultData();
20 $this->assertInternalType( 'array', $data );
21 $this->assertArrayHasKey( 'query', $data );
24 public static function provideAssert() {
25 return [
26 [ false, [], 'user', 'assertuserfailed' ],
27 [ true, [], 'user', false ],
28 [ true, [], 'bot', 'assertbotfailed' ],
29 [ true, [ 'bot' ], 'user', false ],
30 [ true, [ 'bot' ], 'bot', false ],
34 /**
35 * Tests the assert={user|bot} functionality
37 * @covers ApiMain::checkAsserts
38 * @dataProvider provideAssert
39 * @param bool $registered
40 * @param array $rights
41 * @param string $assert
42 * @param string|bool $error False if no error expected
44 public function testAssert( $registered, $rights, $assert, $error ) {
45 $user = new User();
46 if ( $registered ) {
47 $user->setId( 1 );
49 $user->mRights = $rights;
50 try {
51 $this->doApiRequest( [
52 'action' => 'query',
53 'assert' => $assert,
54 ], null, null, $user );
55 $this->assertFalse( $error ); // That no error was expected
56 } catch ( ApiUsageException $e ) {
57 $this->assertTrue( self::apiExceptionHasCode( $e, $error ) );
61 /**
62 * Tests the assertuser= functionality
64 * @covers ApiMain::checkAsserts
66 public function testAssertUser() {
67 $user = $this->getTestUser()->getUser();
68 $this->doApiRequest( [
69 'action' => 'query',
70 'assertuser' => $user->getName(),
71 ], null, null, $user );
73 try {
74 $this->doApiRequest( [
75 'action' => 'query',
76 'assertuser' => $user->getName() . 'X',
77 ], null, null, $user );
78 $this->fail( 'Expected exception not thrown' );
79 } catch ( ApiUsageException $e ) {
80 $this->assertTrue( self::apiExceptionHasCode( $e, 'assertnameduserfailed' ) );
84 /**
85 * Test if all classes in the main module manager exists
87 public function testClassNamesInModuleManager() {
88 $api = new ApiMain(
89 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
91 $modules = $api->getModuleManager()->getNamesWithClasses();
93 foreach ( $modules as $name => $class ) {
94 $this->assertTrue(
95 class_exists( $class ),
96 'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
102 * Test HTTP precondition headers
104 * @covers ApiMain::checkConditionalRequestHeaders
105 * @dataProvider provideCheckConditionalRequestHeaders
106 * @param array $headers HTTP headers
107 * @param array $conditions Return data for ApiBase::getConditionalRequestData
108 * @param int $status Expected response status
109 * @param bool $post Request is a POST
111 public function testCheckConditionalRequestHeaders(
112 $headers, $conditions, $status, $post = false
114 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
115 $request->setHeaders( $headers );
116 $request->response()->statusHeader( 200 ); // Why doesn't it default?
118 $context = $this->apiContext->newTestContext( $request, null );
119 $api = new ApiMain( $context );
120 $priv = TestingAccessWrapper::newFromObject( $api );
121 $priv->mInternalMode = false;
123 $module = $this->getMockBuilder( 'ApiBase' )
124 ->setConstructorArgs( [ $api, 'mock' ] )
125 ->setMethods( [ 'getConditionalRequestData' ] )
126 ->getMockForAbstractClass();
127 $module->expects( $this->any() )
128 ->method( 'getConditionalRequestData' )
129 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
130 return isset( $conditions[$condition] ) ? $conditions[$condition] : null;
131 } ) );
133 $ret = $priv->checkConditionalRequestHeaders( $module );
135 $this->assertSame( $status, $request->response()->getStatusCode() );
136 $this->assertSame( $status === 200, $ret );
139 public static function provideCheckConditionalRequestHeaders() {
140 $now = time();
142 return [
143 // Non-existing from module is ignored
144 [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
145 [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
147 // No headers
151 'etag' => '""',
152 'last-modified' => '20150815000000',
157 // Basic If-None-Match
158 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
159 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
160 [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
161 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
162 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
164 // Pointless, but supported
165 [ [ 'If-None-Match' => '*' ], [], 304 ],
167 // Basic If-Modified-Since
168 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
169 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
170 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
171 [ 'last-modified' => wfTimestamp( TS_MW, $now ) ], 304 ],
172 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
173 [ 'last-modified' => wfTimestamp( TS_MW, $now + 1 ) ], 200 ],
175 // If-Modified-Since ignored when If-None-Match is given too
176 [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
177 [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
178 [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
179 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
181 // Ignored for POST
182 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200, true ],
183 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
184 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200, true ],
186 // Other date formats allowed by the RFC
187 [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
188 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
189 [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
190 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
192 // Old browser extension to HTTP/1.0
193 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) . '; length=123' ],
194 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
196 // Invalid date formats should be ignored
197 [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
198 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
203 * Test conditional headers output
204 * @dataProvider provideConditionalRequestHeadersOutput
205 * @param array $conditions Return data for ApiBase::getConditionalRequestData
206 * @param array $headers Expected output headers
207 * @param bool $isError $isError flag
208 * @param bool $post Request is a POST
210 public function testConditionalRequestHeadersOutput(
211 $conditions, $headers, $isError = false, $post = false
213 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
214 $response = $request->response();
216 $api = new ApiMain( $request );
217 $priv = TestingAccessWrapper::newFromObject( $api );
218 $priv->mInternalMode = false;
220 $module = $this->getMockBuilder( 'ApiBase' )
221 ->setConstructorArgs( [ $api, 'mock' ] )
222 ->setMethods( [ 'getConditionalRequestData' ] )
223 ->getMockForAbstractClass();
224 $module->expects( $this->any() )
225 ->method( 'getConditionalRequestData' )
226 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
227 return isset( $conditions[$condition] ) ? $conditions[$condition] : null;
228 } ) );
229 $priv->mModule = $module;
231 $priv->sendCacheHeaders( $isError );
233 foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
234 $this->assertEquals(
235 isset( $headers[$header] ) ? $headers[$header] : null,
236 $response->getHeader( $header ),
237 $header
242 public static function provideConditionalRequestHeadersOutput() {
243 return [
249 [ 'etag' => '"foo"' ],
250 [ 'ETag' => '"foo"' ]
253 [ 'last-modified' => '20150818000102' ],
254 [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
257 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
258 [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
261 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
263 true,
266 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
268 false,
269 true,
275 * @covers ApiMain::lacksSameOriginSecurity
277 public function testLacksSameOriginSecurity() {
278 // Basic test
279 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
280 $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
282 // JSONp
283 $main = new ApiMain(
284 new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
286 $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
288 // Header
289 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
290 $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
291 $main = new ApiMain( $request );
292 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
294 // Hook
295 $this->mergeMwGlobalArrayValue( 'wgHooks', [
296 'RequestHasSameOriginSecurity' => [ function () {
297 return false;
299 ] );
300 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
301 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
305 * Test proper creation of the ApiErrorFormatter
306 * @covers ApiMain::__construct
307 * @dataProvider provideApiErrorFormatterCreation
308 * @param array $request Request parameters
309 * @param array $expect Expected data
310 * - uselang: ApiMain language
311 * - class: ApiErrorFormatter class
312 * - lang: ApiErrorFormatter language
313 * - format: ApiErrorFormatter format
314 * - usedb: ApiErrorFormatter use-database flag
316 public function testApiErrorFormatterCreation( array $request, array $expect ) {
317 $context = new RequestContext();
318 $context->setRequest( new FauxRequest( $request ) );
319 $context->setLanguage( 'ru' );
321 $main = new ApiMain( $context );
322 $formatter = $main->getErrorFormatter();
323 $wrappedFormatter = TestingAccessWrapper::newFromObject( $formatter );
325 $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
326 $this->assertInstanceOf( $expect['class'], $formatter );
327 $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
328 $this->assertSame( $expect['format'], $wrappedFormatter->format );
329 $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB );
332 public static function provideApiErrorFormatterCreation() {
333 global $wgContLang;
335 return [
336 'Default (BC)' => [ [], [
337 'uselang' => 'ru',
338 'class' => ApiErrorFormatter_BackCompat::class,
339 'lang' => 'en',
340 'format' => 'none',
341 'usedb' => false,
342 ] ],
343 'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
344 'uselang' => 'ru',
345 'class' => ApiErrorFormatter_BackCompat::class,
346 'lang' => 'en',
347 'format' => 'none',
348 'usedb' => false,
349 ] ],
350 'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
351 'uselang' => 'ru',
352 'class' => ApiErrorFormatter_BackCompat::class,
353 'lang' => 'en',
354 'format' => 'none',
355 'usedb' => false,
356 ] ],
357 'Basic' => [ [ 'errorformat' => 'wikitext' ], [
358 'uselang' => 'ru',
359 'class' => ApiErrorFormatter::class,
360 'lang' => 'ru',
361 'format' => 'wikitext',
362 'usedb' => false,
363 ] ],
364 'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
365 'uselang' => 'fr',
366 'class' => ApiErrorFormatter::class,
367 'lang' => 'fr',
368 'format' => 'plaintext',
369 'usedb' => false,
370 ] ],
371 'Explicitly follows uselang' => [
372 [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
374 'uselang' => 'fr',
375 'class' => ApiErrorFormatter::class,
376 'lang' => 'fr',
377 'format' => 'plaintext',
378 'usedb' => false,
381 'uselang=content' => [
382 [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
384 'uselang' => $wgContLang->getCode(),
385 'class' => ApiErrorFormatter::class,
386 'lang' => $wgContLang->getCode(),
387 'format' => 'plaintext',
388 'usedb' => false,
391 'errorlang=content' => [
392 [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
394 'uselang' => 'ru',
395 'class' => ApiErrorFormatter::class,
396 'lang' => $wgContLang->getCode(),
397 'format' => 'plaintext',
398 'usedb' => false,
401 'Explicit parameters' => [
402 [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
404 'uselang' => 'ru',
405 'class' => ApiErrorFormatter::class,
406 'lang' => 'de',
407 'format' => 'html',
408 'usedb' => true,
411 'Explicit parameters override uselang' => [
412 [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
414 'uselang' => 'fr',
415 'class' => ApiErrorFormatter::class,
416 'lang' => 'de',
417 'format' => 'raw',
418 'usedb' => false,
421 'Bogus language doesn\'t explode' => [
422 [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
424 'uselang' => 'en',
425 'class' => ApiErrorFormatter::class,
426 'lang' => 'en',
427 'format' => 'none',
428 'usedb' => false,
431 'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
432 'uselang' => 'ru',
433 'class' => ApiErrorFormatter_BackCompat::class,
434 'lang' => 'en',
435 'format' => 'none',
436 'usedb' => false,
437 ] ],
442 * @covers ApiMain::errorMessagesFromException
443 * @covers ApiMain::substituteResultWithError
444 * @dataProvider provideExceptionErrors
445 * @param Exception $exception
446 * @param array $expectReturn
447 * @param array $expectResult
449 public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
450 $context = new RequestContext();
451 $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
452 $context->setLanguage( 'en' );
453 $context->setConfig( new MultiConfig( [
454 new HashConfig( [ 'ShowHostnames' => true, 'ShowSQLErrors' => false ] ),
455 $context->getConfig()
456 ] ) );
458 $main = new ApiMain( $context );
459 $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
460 $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
462 $ret = TestingAccessWrapper::newFromObject( $main )->substituteResultWithError( $error );
463 $this->assertSame( $expectReturn, $ret );
465 // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
466 // so let's try ->assertEquals().
467 $this->assertEquals(
468 $expectResult,
469 $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
473 // Not static so $this->getMock() can be used
474 public function provideExceptionErrors() {
475 $reqId = WebRequest::getRequestId();
476 $doclink = wfExpandUrl( wfScript( 'api' ) );
478 $ex = new InvalidArgumentException( 'Random exception' );
479 $trace = wfMessage( 'api-exception-trace',
480 get_class( $ex ),
481 $ex->getFile(),
482 $ex->getLine(),
483 MWExceptionHandler::getRedactedTraceAsString( $ex )
484 )->inLanguage( 'en' )->useDatabase( false )->text();
486 $dbex = new DBQueryError( $this->getMock( 'IDatabase' ), 'error', 1234, 'SELECT 1', __METHOD__ );
487 $dbtrace = wfMessage( 'api-exception-trace',
488 get_class( $dbex ),
489 $dbex->getFile(),
490 $dbex->getLine(),
491 MWExceptionHandler::getRedactedTraceAsString( $dbex )
492 )->inLanguage( 'en' )->useDatabase( false )->text();
494 $apiEx1 = new ApiUsageException( null,
495 StatusValue::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
496 TestingAccessWrapper::newFromObject( $apiEx1 )->modulePath = 'foo+bar';
497 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
498 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
499 $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
501 return [
503 $ex,
504 [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
506 'warnings' => [
507 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
509 'errors' => [
510 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
512 'code' => 'internal_api_error_InvalidArgumentException',
513 'text' => "[$reqId] Exception caught: Random exception",
516 'trace' => $trace,
517 'servedby' => wfHostname(),
521 $dbex,
522 [ 'existing-error', 'internal_api_error_DBQueryError' ],
524 'warnings' => [
525 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
527 'errors' => [
528 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
530 'code' => 'internal_api_error_DBQueryError',
531 'text' => "[$reqId] Database query error.",
534 'trace' => $dbtrace,
535 'servedby' => wfHostname(),
539 new UsageException( 'Usage exception!', 'ue', 0, [ 'foo' => 'bar' ] ),
540 [ 'existing-error', 'ue' ],
542 'warnings' => [
543 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
545 'errors' => [
546 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
547 [ 'code' => 'ue', 'text' => "Usage exception!", 'data' => [ 'foo' => 'bar' ] ]
549 'docref' => "See $doclink for API usage.",
550 'servedby' => wfHostname(),
554 $apiEx1,
555 [ 'existing-error', 'sv-error1', 'sv-error2' ],
557 'warnings' => [
558 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
559 [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
560 [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
562 'errors' => [
563 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
564 [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
565 [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
567 'docref' => "See $doclink for API usage.",
568 'servedby' => wfHostname(),