3 use Wikimedia\TestingAccessWrapper
;
12 class ApiMainTest
extends ApiTestCase
{
15 * Test that the API will accept a FauxRequest and execute.
17 public function testApi() {
19 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
22 $data = $api->getResult()->getResultData();
23 $this->assertInternalType( 'array', $data );
24 $this->assertArrayHasKey( 'query', $data );
27 public static function provideAssert() {
29 [ false, [], 'user', 'assertuserfailed' ],
30 [ true, [], 'user', false ],
31 [ true, [], 'bot', 'assertbotfailed' ],
32 [ true, [ 'bot' ], 'user', false ],
33 [ true, [ 'bot' ], 'bot', false ],
38 * Tests the assert={user|bot} functionality
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
47 public function testAssert( $registered, $rights, $assert, $error ) {
49 $user = $this->getMutableTestUser()->getUser();
50 $user->load(); // load before setting mRights
54 $user->mRights
= $rights;
56 $this->doApiRequest( [
59 ], null, null, $user );
60 $this->assertFalse( $error ); // That no error was expected
61 } catch ( ApiUsageException
$e ) {
62 $this->assertTrue( self
::apiExceptionHasCode( $e, $error ),
63 "Error '{$e->getMessage()}' matched expected '$error'" );
68 * Tests the assertuser= functionality
70 * @covers ApiMain::checkAsserts
72 public function testAssertUser() {
73 $user = $this->getTestUser()->getUser();
74 $this->doApiRequest( [
76 'assertuser' => $user->getName(),
77 ], null, null, $user );
80 $this->doApiRequest( [
82 'assertuser' => $user->getName() . 'X',
83 ], null, null, $user );
84 $this->fail( 'Expected exception not thrown' );
85 } catch ( ApiUsageException
$e ) {
86 $this->assertTrue( self
::apiExceptionHasCode( $e, 'assertnameduserfailed' ) );
91 * Test if all classes in the main module manager exists
93 public function testClassNamesInModuleManager() {
95 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
97 $modules = $api->getModuleManager()->getNamesWithClasses();
99 foreach ( $modules as $name => $class ) {
101 class_exists( $class ),
102 'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
108 * Test HTTP precondition headers
110 * @covers ApiMain::checkConditionalRequestHeaders
111 * @dataProvider provideCheckConditionalRequestHeaders
112 * @param array $headers HTTP headers
113 * @param array $conditions Return data for ApiBase::getConditionalRequestData
114 * @param int $status Expected response status
115 * @param bool $post Request is a POST
117 public function testCheckConditionalRequestHeaders(
118 $headers, $conditions, $status, $post = false
120 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
121 $request->setHeaders( $headers );
122 $request->response()->statusHeader( 200 ); // Why doesn't it default?
124 $context = $this->apiContext
->newTestContext( $request, null );
125 $api = new ApiMain( $context );
126 $priv = TestingAccessWrapper
::newFromObject( $api );
127 $priv->mInternalMode
= false;
129 $module = $this->getMockBuilder( 'ApiBase' )
130 ->setConstructorArgs( [ $api, 'mock' ] )
131 ->setMethods( [ 'getConditionalRequestData' ] )
132 ->getMockForAbstractClass();
133 $module->expects( $this->any() )
134 ->method( 'getConditionalRequestData' )
135 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
136 return isset( $conditions[$condition] ) ?
$conditions[$condition] : null;
139 $ret = $priv->checkConditionalRequestHeaders( $module );
141 $this->assertSame( $status, $request->response()->getStatusCode() );
142 $this->assertSame( $status === 200, $ret );
145 public static function provideCheckConditionalRequestHeaders() {
149 // Non-existing from module is ignored
150 [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
151 [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
158 'last-modified' => '20150815000000',
163 // Basic If-None-Match
164 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
165 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
166 [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
167 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
168 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
170 // Pointless, but supported
171 [ [ 'If-None-Match' => '*' ], [], 304 ],
173 // Basic If-Modified-Since
174 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
175 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
176 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
177 [ 'last-modified' => wfTimestamp( TS_MW
, $now ) ], 304 ],
178 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
179 [ 'last-modified' => wfTimestamp( TS_MW
, $now +
1 ) ], 200 ],
181 // If-Modified-Since ignored when If-None-Match is given too
182 [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
183 [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
184 [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
185 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
188 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200, true ],
189 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
190 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200, true ],
192 // Other date formats allowed by the RFC
193 [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
194 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
195 [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
196 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
198 // Old browser extension to HTTP/1.0
199 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) . '; length=123' ],
200 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
202 // Invalid date formats should be ignored
203 [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
204 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
209 * Test conditional headers output
210 * @dataProvider provideConditionalRequestHeadersOutput
211 * @param array $conditions Return data for ApiBase::getConditionalRequestData
212 * @param array $headers Expected output headers
213 * @param bool $isError $isError flag
214 * @param bool $post Request is a POST
216 public function testConditionalRequestHeadersOutput(
217 $conditions, $headers, $isError = false, $post = false
219 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
220 $response = $request->response();
222 $api = new ApiMain( $request );
223 $priv = TestingAccessWrapper
::newFromObject( $api );
224 $priv->mInternalMode
= false;
226 $module = $this->getMockBuilder( 'ApiBase' )
227 ->setConstructorArgs( [ $api, 'mock' ] )
228 ->setMethods( [ 'getConditionalRequestData' ] )
229 ->getMockForAbstractClass();
230 $module->expects( $this->any() )
231 ->method( 'getConditionalRequestData' )
232 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
233 return isset( $conditions[$condition] ) ?
$conditions[$condition] : null;
235 $priv->mModule
= $module;
237 $priv->sendCacheHeaders( $isError );
239 foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
241 isset( $headers[$header] ) ?
$headers[$header] : null,
242 $response->getHeader( $header ),
248 public static function provideConditionalRequestHeadersOutput() {
255 [ 'etag' => '"foo"' ],
256 [ 'ETag' => '"foo"' ]
259 [ 'last-modified' => '20150818000102' ],
260 [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
263 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
264 [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
267 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
272 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
281 * @covers ApiMain::lacksSameOriginSecurity
283 public function testLacksSameOriginSecurity() {
285 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
286 $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
290 new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
292 $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
295 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
296 $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
297 $main = new ApiMain( $request );
298 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
301 $this->mergeMwGlobalArrayValue( 'wgHooks', [
302 'RequestHasSameOriginSecurity' => [ function () {
306 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
307 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
311 * Test proper creation of the ApiErrorFormatter
312 * @covers ApiMain::__construct
313 * @dataProvider provideApiErrorFormatterCreation
314 * @param array $request Request parameters
315 * @param array $expect Expected data
316 * - uselang: ApiMain language
317 * - class: ApiErrorFormatter class
318 * - lang: ApiErrorFormatter language
319 * - format: ApiErrorFormatter format
320 * - usedb: ApiErrorFormatter use-database flag
322 public function testApiErrorFormatterCreation( array $request, array $expect ) {
323 $context = new RequestContext();
324 $context->setRequest( new FauxRequest( $request ) );
325 $context->setLanguage( 'ru' );
327 $main = new ApiMain( $context );
328 $formatter = $main->getErrorFormatter();
329 $wrappedFormatter = TestingAccessWrapper
::newFromObject( $formatter );
331 $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
332 $this->assertInstanceOf( $expect['class'], $formatter );
333 $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
334 $this->assertSame( $expect['format'], $wrappedFormatter->format
);
335 $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB
);
338 public static function provideApiErrorFormatterCreation() {
340 'Default (BC)' => [ [], [
342 'class' => ApiErrorFormatter_BackCompat
::class,
347 'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
349 'class' => ApiErrorFormatter_BackCompat
::class,
354 'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
356 'class' => ApiErrorFormatter_BackCompat
::class,
361 'Basic' => [ [ 'errorformat' => 'wikitext' ], [
363 'class' => ApiErrorFormatter
::class,
365 'format' => 'wikitext',
368 'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
370 'class' => ApiErrorFormatter
::class,
372 'format' => 'plaintext',
375 'Explicitly follows uselang' => [
376 [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
379 'class' => ApiErrorFormatter
::class,
381 'format' => 'plaintext',
385 'uselang=content' => [
386 [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
389 'class' => ApiErrorFormatter
::class,
391 'format' => 'plaintext',
395 'errorlang=content' => [
396 [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
399 'class' => ApiErrorFormatter
::class,
401 'format' => 'plaintext',
405 'Explicit parameters' => [
406 [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
409 'class' => ApiErrorFormatter
::class,
415 'Explicit parameters override uselang' => [
416 [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
419 'class' => ApiErrorFormatter
::class,
425 'Bogus language doesn\'t explode' => [
426 [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
429 'class' => ApiErrorFormatter
::class,
435 'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
437 'class' => ApiErrorFormatter_BackCompat
::class,
446 * @covers ApiMain::errorMessagesFromException
447 * @covers ApiMain::substituteResultWithError
448 * @dataProvider provideExceptionErrors
449 * @param Exception $exception
450 * @param array $expectReturn
451 * @param array $expectResult
453 public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
454 $context = new RequestContext();
455 $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
456 $context->setLanguage( 'en' );
457 $context->setConfig( new MultiConfig( [
459 'ShowHostnames' => true, 'ShowSQLErrors' => false,
460 'ShowExceptionDetails' => true, 'ShowDBErrorBacktrace' => true,
462 $context->getConfig()
465 $main = new ApiMain( $context );
466 $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
467 $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
469 $ret = TestingAccessWrapper
::newFromObject( $main )->substituteResultWithError( $error );
470 $this->assertSame( $expectReturn, $ret );
472 // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
473 // so let's try ->assertEquals().
476 $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
480 // Not static so $this can be used
481 public function provideExceptionErrors() {
482 $reqId = WebRequest
::getRequestId();
483 $doclink = wfExpandUrl( wfScript( 'api' ) );
485 $ex = new InvalidArgumentException( 'Random exception' );
486 $trace = wfMessage( 'api-exception-trace',
490 MWExceptionHandler
::getRedactedTraceAsString( $ex )
491 )->inLanguage( 'en' )->useDatabase( false )->text();
493 $dbex = new DBQueryError(
494 $this->createMock( 'IDatabase' ),
495 'error', 1234, 'SELECT 1', __METHOD__
);
496 $dbtrace = wfMessage( 'api-exception-trace',
500 MWExceptionHandler
::getRedactedTraceAsString( $dbex )
501 )->inLanguage( 'en' )->useDatabase( false )->text();
503 MediaWiki\
suppressWarnings();
504 $usageEx = new UsageException( 'Usage exception!', 'ue', 0, [ 'foo' => 'bar' ] );
505 MediaWiki\restoreWarnings
();
507 $apiEx1 = new ApiUsageException( null,
508 StatusValue
::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
509 TestingAccessWrapper
::newFromObject( $apiEx1 )->modulePath
= 'foo+bar';
510 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
511 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
512 $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
517 [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
520 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
523 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
525 'code' => 'internal_api_error_InvalidArgumentException',
526 'text' => "[$reqId] Exception caught: Random exception",
530 'servedby' => wfHostname(),
535 [ 'existing-error', 'internal_api_error_DBQueryError' ],
538 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
541 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
543 'code' => 'internal_api_error_DBQueryError',
544 'text' => "[$reqId] Database query error.",
548 'servedby' => wfHostname(),
553 [ 'existing-error', 'ue' ],
556 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
559 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
560 [ 'code' => 'ue', 'text' => "Usage exception!", 'data' => [ 'foo' => 'bar' ] ]
562 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
563 "list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> " .
564 "for notice of API deprecations and breaking changes.",
565 'servedby' => wfHostname(),
570 [ 'existing-error', 'sv-error1', 'sv-error2' ],
573 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
574 [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
575 [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
578 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
579 [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
580 [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
582 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
583 "list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> " .
584 "for notice of API deprecations and breaking changes.",
585 'servedby' => wfHostname(),