9 class ApiMainTest
extends ApiTestCase
{
12 * Test that the API will accept a FauxRequest and execute.
14 public function testApi() {
16 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
19 $data = $api->getResult()->getResultData();
20 $this->assertInternalType( 'array', $data );
21 $this->assertArrayHasKey( 'query', $data );
24 public static function provideAssert() {
26 [ false, [], 'user', 'assertuserfailed' ],
27 [ true, [], 'user', false ],
28 [ true, [], 'bot', 'assertbotfailed' ],
29 [ true, [ 'bot' ], 'user', false ],
30 [ true, [ 'bot' ], 'bot', false ],
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 ) {
49 $user->mRights
= $rights;
51 $this->doApiRequest( [
54 ], null, null, $user );
55 $this->assertFalse( $error ); // That no error was expected
56 } catch ( ApiUsageException
$e ) {
57 $this->assertTrue( self
::apiExceptionHasCode( $e, $error ) );
62 * Tests the assertuser= functionality
64 * @covers ApiMain::checkAsserts
66 public function testAssertUser() {
67 $user = $this->getTestUser()->getUser();
68 $this->doApiRequest( [
70 'assertuser' => $user->getName(),
71 ], null, null, $user );
74 $this->doApiRequest( [
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' ) );
85 * Test if all classes in the main module manager exists
87 public function testClassNamesInModuleManager() {
89 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
91 $modules = $api->getModuleManager()->getNamesWithClasses();
93 foreach ( $modules as $name => $class ) {
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;
133 $ret = $priv->checkConditionalRequestHeaders( $module );
135 $this->assertSame( $status, $request->response()->getStatusCode() );
136 $this->assertSame( $status === 200, $ret );
139 public static function provideCheckConditionalRequestHeaders() {
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 ],
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 ],
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;
229 $priv->mModule
= $module;
231 $priv->sendCacheHeaders( $isError );
233 foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
235 isset( $headers[$header] ) ?
$headers[$header] : null,
236 $response->getHeader( $header ),
242 public static function provideConditionalRequestHeadersOutput() {
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' ],
266 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
275 * @covers ApiMain::lacksSameOriginSecurity
277 public function testLacksSameOriginSecurity() {
279 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
280 $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
284 new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
286 $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
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' );
295 $this->mergeMwGlobalArrayValue( 'wgHooks', [
296 'RequestHasSameOriginSecurity' => [ function () {
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() {
336 'Default (BC)' => [ [], [
338 'class' => ApiErrorFormatter_BackCompat
::class,
343 'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
345 'class' => ApiErrorFormatter_BackCompat
::class,
350 'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
352 'class' => ApiErrorFormatter_BackCompat
::class,
357 'Basic' => [ [ 'errorformat' => 'wikitext' ], [
359 'class' => ApiErrorFormatter
::class,
361 'format' => 'wikitext',
364 'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
366 'class' => ApiErrorFormatter
::class,
368 'format' => 'plaintext',
371 'Explicitly follows uselang' => [
372 [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
375 'class' => ApiErrorFormatter
::class,
377 'format' => 'plaintext',
381 'uselang=content' => [
382 [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
384 'uselang' => $wgContLang->getCode(),
385 'class' => ApiErrorFormatter
::class,
386 'lang' => $wgContLang->getCode(),
387 'format' => 'plaintext',
391 'errorlang=content' => [
392 [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
395 'class' => ApiErrorFormatter
::class,
396 'lang' => $wgContLang->getCode(),
397 'format' => 'plaintext',
401 'Explicit parameters' => [
402 [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
405 'class' => ApiErrorFormatter
::class,
411 'Explicit parameters override uselang' => [
412 [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
415 'class' => ApiErrorFormatter
::class,
421 'Bogus language doesn\'t explode' => [
422 [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
425 'class' => ApiErrorFormatter
::class,
431 'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
433 'class' => ApiErrorFormatter_BackCompat
::class,
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( [
455 'ShowHostnames' => true, 'ShowSQLErrors' => false,
456 'ShowExceptionDetails' => true, 'ShowDBErrorBacktrace' => true,
458 $context->getConfig()
461 $main = new ApiMain( $context );
462 $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
463 $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
465 $ret = TestingAccessWrapper
::newFromObject( $main )->substituteResultWithError( $error );
466 $this->assertSame( $expectReturn, $ret );
468 // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
469 // so let's try ->assertEquals().
472 $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
476 // Not static so $this->getMock() can be used
477 public function provideExceptionErrors() {
478 $reqId = WebRequest
::getRequestId();
479 $doclink = wfExpandUrl( wfScript( 'api' ) );
481 $ex = new InvalidArgumentException( 'Random exception' );
482 $trace = wfMessage( 'api-exception-trace',
486 MWExceptionHandler
::getRedactedTraceAsString( $ex )
487 )->inLanguage( 'en' )->useDatabase( false )->text();
489 $dbex = new DBQueryError( $this->getMock( 'IDatabase' ), 'error', 1234, 'SELECT 1', __METHOD__
);
490 $dbtrace = wfMessage( 'api-exception-trace',
494 MWExceptionHandler
::getRedactedTraceAsString( $dbex )
495 )->inLanguage( 'en' )->useDatabase( false )->text();
497 $apiEx1 = new ApiUsageException( null,
498 StatusValue
::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
499 TestingAccessWrapper
::newFromObject( $apiEx1 )->modulePath
= 'foo+bar';
500 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
501 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
502 $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
507 [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
510 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
513 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
515 'code' => 'internal_api_error_InvalidArgumentException',
516 'text' => "[$reqId] Exception caught: Random exception",
520 'servedby' => wfHostname(),
525 [ 'existing-error', 'internal_api_error_DBQueryError' ],
528 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
531 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
533 'code' => 'internal_api_error_DBQueryError',
534 'text' => "[$reqId] Database query error.",
538 'servedby' => wfHostname(),
542 new UsageException( 'Usage exception!', 'ue', 0, [ 'foo' => 'bar' ] ),
543 [ 'existing-error', 'ue' ],
546 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
549 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
550 [ 'code' => 'ue', 'text' => "Usage exception!", 'data' => [ 'foo' => 'bar' ] ]
552 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
553 "list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> " .
554 "for notice of API deprecations and breaking changes.",
555 'servedby' => wfHostname(),
560 [ 'existing-error', 'sv-error1', 'sv-error2' ],
563 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
564 [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
565 [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
568 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
569 [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
570 [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
572 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
573 "list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> " .
574 "for notice of API deprecations and breaking changes.",
575 'servedby' => wfHostname(),