3 use Wikimedia\Rdbms\DBQueryError
;
4 use Wikimedia\TestingAccessWrapper
;
13 class ApiMainTest
extends ApiTestCase
{
16 * Test that the API will accept a FauxRequest and execute.
18 public function testApi() {
20 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
23 $data = $api->getResult()->getResultData();
24 $this->assertInternalType( 'array', $data );
25 $this->assertArrayHasKey( 'query', $data );
28 public function testApiNoParam() {
31 $data = $api->getResult()->getResultData();
32 $this->assertInternalType( 'array', $data );
36 * ApiMain behaves differently if passed a FauxRequest (mInternalMode set
37 * to true) or a proper WebRequest (mInternalMode false). For most tests
38 * we can just set mInternalMode to false using TestingAccessWrapper, but
39 * this doesn't work for the constructor. This method returns an ApiMain
40 * that's been set up in non-internal mode.
42 * Note that calling execute() will print to the console. Wrap it in
43 * ob_start()/ob_end_clean() to prevent this.
45 * @param array $requestData Query parameters for the WebRequest
46 * @param array $headers Headers for the WebRequest
48 private function getNonInternalApiMain( array $requestData, array $headers = [] ) {
49 $req = $this->getMockBuilder( WebRequest
::class )
50 ->setMethods( [ 'response', 'getRawIP' ] )
52 $response = new FauxResponse();
53 $req->method( 'response' )->willReturn( $response );
54 $req->method( 'getRawIP' )->willReturn( '127.0.0.1' );
56 $wrapper = TestingAccessWrapper
::newFromObject( $req );
57 $wrapper->data
= $requestData;
59 $wrapper->headers
= $headers;
62 return new ApiMain( $req );
65 public function testUselang() {
68 $api = $this->getNonInternalApiMain( [
78 $this->assertSame( 'fr', $wgLang->getCode() );
81 public function testNonWhitelistedCorsWithCookies() {
82 $logFile = $this->getNewTempFile();
84 $this->mergeMwGlobalArrayValue( '_COOKIE', [ 'forceHTTPS' => '1' ] );
85 $logger = new TestLogger( true );
86 $this->setLogger( 'cors', $logger );
88 $api = $this->getNonInternalApiMain( [
91 // For some reason multiple origins (which are not allowed in the
92 // WHATWG Fetch spec that supersedes the RFC) are always considered to
94 ], [ 'ORIGIN' => 'https://www.example.com https://www.com.example' ] );
97 [ [ Psr\Log\LogLevel
::WARNING
, 'Non-whitelisted CORS request with session cookies' ] ],
102 public function testSuppressedLogin() {
106 $api = $this->getNonInternalApiMain( [
108 'meta' => 'siteinfo',
116 $this->assertNotSame( $origUser, $wgUser );
117 $this->assertSame( 'true', $api->getContext()->getRequest()->response()
118 ->getHeader( 'MediaWiki-Login-Suppressed' ) );
121 public function testSetContinuationManager() {
122 $api = new ApiMain();
123 $manager = $this->createMock( ApiContinuationManager
::class );
124 $api->setContinuationManager( $manager );
125 $this->assertTrue( true, 'No exception' );
126 return [ $api, $manager ];
130 * @depends testSetContinuationManager
132 public function testSetContinuationManagerTwice( $args ) {
133 $this->setExpectedException( UnexpectedValueException
::class,
134 'ApiMain::setContinuationManager: tried to set manager from ' .
135 'when a manager is already set from ' );
137 list( $api, $manager ) = $args;
138 $api->setContinuationManager( $manager );
141 public function testSetCacheModeUnrecognized() {
142 $api = new ApiMain();
143 $api->setCacheMode( 'unrecognized' );
146 TestingAccessWrapper
::newFromObject( $api )->mCacheMode
,
147 'Unrecognized params must be silently ignored'
151 public function testSetCacheModePrivateWiki() {
152 $this->setGroupPermissions( '*', 'read', false );
154 $wrappedApi = TestingAccessWrapper
::newFromObject( new ApiMain() );
155 $wrappedApi->setCacheMode( 'public' );
156 $this->assertSame( 'private', $wrappedApi->mCacheMode
);
157 $wrappedApi->setCacheMode( 'anon-public-user-private' );
158 $this->assertSame( 'private', $wrappedApi->mCacheMode
);
161 public function testAddRequestedFieldsRequestId() {
162 $req = new FauxRequest( [
164 'meta' => 'siteinfo',
165 'requestid' => '123456',
167 $api = new ApiMain( $req );
169 $this->assertSame( '123456', $api->getResult()->getResultData()['requestid'] );
172 public function testAddRequestedFieldsCurTimestamp() {
173 $req = new FauxRequest( [
175 'meta' => 'siteinfo',
176 'curtimestamp' => '',
178 $api = new ApiMain( $req );
180 $timestamp = $api->getResult()->getResultData()['curtimestamp'];
181 $this->assertLessThanOrEqual( 1, abs( strtotime( $timestamp ) - time() ) );
184 public function testAddRequestedFieldsResponseLangInfo() {
185 $req = new FauxRequest( [
187 'meta' => 'siteinfo',
188 // errorlang is ignored if errorformat is not specified
189 'errorformat' => 'plaintext',
192 'responselanginfo' => '',
194 $api = new ApiMain( $req );
196 $data = $api->getResult()->getResultData();
197 $this->assertSame( 'fr', $data['uselang'] );
198 $this->assertSame( 'ja', $data['errorlang'] );
201 public function testSetupModuleUnknown() {
202 $this->setExpectedException( ApiUsageException
::class,
203 'Unrecognized value for parameter "action": unknownaction.' );
205 $req = new FauxRequest( [ 'action' => 'unknownaction' ] );
206 $api = new ApiMain( $req );
210 public function testSetupModuleNoTokenProvided() {
211 $this->setExpectedException( ApiUsageException
::class,
212 'The "token" parameter must be set.' );
214 $req = new FauxRequest( [
216 'title' => 'New page',
217 'text' => 'Some text',
219 $api = new ApiMain( $req );
223 public function testSetupModuleInvalidTokenProvided() {
224 $this->setExpectedException( ApiUsageException
::class, 'Invalid CSRF token.' );
226 $req = new FauxRequest( [
228 'title' => 'New page',
229 'text' => 'Some text',
230 'token' => "This isn't a real token!",
232 $api = new ApiMain( $req );
236 public function testSetupModuleNeedsTokenTrue() {
237 $this->setExpectedException( MWException
::class,
238 "Module 'testmodule' must be updated for the new token handling. " .
239 "See documentation for ApiBase::needsToken for details." );
241 $mock = $this->createMock( ApiBase
::class );
242 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
243 $mock->method( 'needsToken' )->willReturn( true );
245 $api = new ApiMain( new FauxRequest( [ 'action' => 'testmodule' ] ) );
246 $api->getModuleManager()->addModule( 'testmodule', 'action', get_class( $mock ),
247 function () use ( $mock ) {
254 public function testSetupModuleNeedsTokenNeedntBePosted() {
255 $this->setExpectedException( MWException
::class,
256 "Module 'testmodule' must require POST to use tokens." );
258 $mock = $this->createMock( ApiBase
::class );
259 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
260 $mock->method( 'needsToken' )->willReturn( 'csrf' );
261 $mock->method( 'mustBePosted' )->willReturn( false );
263 $api = new ApiMain( new FauxRequest( [ 'action' => 'testmodule' ] ) );
264 $api->getModuleManager()->addModule( 'testmodule', 'action', get_class( $mock ),
265 function () use ( $mock ) {
272 public function testCheckMaxLagFailed() {
273 // It's hard to mock the LoadBalancer properly, so instead we'll mock
274 // checkMaxLag (which is tested directly in other tests below).
275 $req = new FauxRequest( [
277 'meta' => 'siteinfo',
280 $mock = $this->getMockBuilder( ApiMain
::class )
281 ->setConstructorArgs( [ $req ] )
282 ->setMethods( [ 'checkMaxLag' ] )
284 $mock->method( 'checkMaxLag' )->willReturn( false );
288 $this->assertArrayNotHasKey( 'query', $mock->getResult()->getResultData() );
291 public function testCheckConditionalRequestHeadersFailed() {
292 // The detailed checking of all cases of checkConditionalRequestHeaders
293 // is below in testCheckConditionalRequestHeaders(), which calls the
294 // method directly. Here we just check that it will stop execution if
298 $this->setMwGlobals( 'wgCacheEpoch', '20030516000000' );
300 $mock = $this->createMock( ApiBase
::class );
301 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
302 $mock->method( 'getConditionalRequestData' )
303 ->willReturn( wfTimestamp( TS_MW
, $now - 3600 ) );
304 $mock->expects( $this->exactly( 0 ) )->method( 'execute' );
306 $req = new FauxRequest( [
307 'action' => 'testmodule',
309 $req->setHeader( 'If-Modified-Since', wfTimestamp( TS_RFC2822
, $now - 3600 ) );
310 $req->setRequestURL( "http://localhost" );
312 $api = new ApiMain( $req );
313 $api->getModuleManager()->addModule( 'testmodule', 'action', get_class( $mock ),
314 function () use ( $mock ) {
319 $wrapper = TestingAccessWrapper
::newFromObject( $api );
320 $wrapper->mInternalMode
= false;
327 private function doTestCheckMaxLag( $lag ) {
328 $mockLB = $this->getMockBuilder( LoadBalancer
::class )
329 ->disableOriginalConstructor()
330 ->setMethods( [ 'getMaxLag', '__destruct' ] )
332 $mockLB->method( 'getMaxLag' )->willReturn( [ 'somehost', $lag ] );
333 $this->setService( 'DBLoadBalancer', $mockLB );
335 $req = new FauxRequest();
337 $api = new ApiMain( $req );
338 $wrapper = TestingAccessWrapper
::newFromObject( $api );
340 $mockModule = $this->createMock( ApiBase
::class );
341 $mockModule->method( 'shouldCheckMaxLag' )->willReturn( true );
344 $wrapper->checkMaxLag( $mockModule, [ 'maxlag' => 3 ] );
347 $this->assertSame( '5', $req->response()->getHeader( 'Retry-After' ) );
348 $this->assertSame( (string)$lag, $req->response()->getHeader( 'X-Database-Lag' ) );
353 public function testCheckMaxLagOkay() {
354 $this->doTestCheckMaxLag( 3 );
356 // No exception, we're happy
357 $this->assertTrue( true );
360 public function testCheckMaxLagExceeded() {
361 $this->setExpectedException( ApiUsageException
::class,
362 'Waiting for a database server: 4 seconds lagged.' );
364 $this->setMwGlobals( 'wgShowHostnames', false );
366 $this->doTestCheckMaxLag( 4 );
369 public function testCheckMaxLagExceededWithHostNames() {
370 $this->setExpectedException( ApiUsageException
::class,
371 'Waiting for somehost: 4 seconds lagged.' );
373 $this->setMwGlobals( 'wgShowHostnames', true );
375 $this->doTestCheckMaxLag( 4 );
378 public static function provideAssert() {
380 [ false, [], 'user', 'assertuserfailed' ],
381 [ true, [], 'user', false ],
382 [ true, [], 'bot', 'assertbotfailed' ],
383 [ true, [ 'bot' ], 'user', false ],
384 [ true, [ 'bot' ], 'bot', false ],
389 * Tests the assert={user|bot} functionality
391 * @dataProvider provideAssert
392 * @param bool $registered
393 * @param array $rights
394 * @param string $assert
395 * @param string|bool $error False if no error expected
397 public function testAssert( $registered, $rights, $assert, $error ) {
399 $user = $this->getMutableTestUser()->getUser();
400 $user->load(); // load before setting mRights
404 $user->mRights
= $rights;
406 $this->doApiRequest( [
409 ], null, null, $user );
410 $this->assertFalse( $error ); // That no error was expected
411 } catch ( ApiUsageException
$e ) {
412 $this->assertTrue( self
::apiExceptionHasCode( $e, $error ),
413 "Error '{$e->getMessage()}' matched expected '$error'" );
418 * Tests the assertuser= functionality
420 public function testAssertUser() {
421 $user = $this->getTestUser()->getUser();
422 $this->doApiRequest( [
424 'assertuser' => $user->getName(),
425 ], null, null, $user );
428 $this->doApiRequest( [
430 'assertuser' => $user->getName() . 'X',
431 ], null, null, $user );
432 $this->fail( 'Expected exception not thrown' );
433 } catch ( ApiUsageException
$e ) {
434 $this->assertTrue( self
::apiExceptionHasCode( $e, 'assertnameduserfailed' ) );
439 * Test that 'assert' is processed before module errors
441 public function testAssertBeforeModule() {
442 // Sanity check that the query without assert throws too-many-titles
444 $this->doApiRequest( [
446 'titles' => implode( '|', range( 1, ApiBase
::LIMIT_SML1 +
1 ) ),
447 ], null, null, new User
);
448 $this->fail( 'Expected exception not thrown' );
449 } catch ( ApiUsageException
$e ) {
450 $this->assertTrue( self
::apiExceptionHasCode( $e, 'too-many-titles' ), 'sanity check' );
453 // Now test that the assert happens first
455 $this->doApiRequest( [
457 'titles' => implode( '|', range( 1, ApiBase
::LIMIT_SML1 +
1 ) ),
459 ], null, null, new User
);
460 $this->fail( 'Expected exception not thrown' );
461 } catch ( ApiUsageException
$e ) {
462 $this->assertTrue( self
::apiExceptionHasCode( $e, 'assertuserfailed' ),
463 "Error '{$e->getMessage()}' matched expected 'assertuserfailed'" );
468 * Test if all classes in the main module manager exists
470 public function testClassNamesInModuleManager() {
472 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
474 $modules = $api->getModuleManager()->getNamesWithClasses();
476 foreach ( $modules as $name => $class ) {
478 class_exists( $class ),
479 'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
485 * Test HTTP precondition headers
487 * @dataProvider provideCheckConditionalRequestHeaders
488 * @param array $headers HTTP headers
489 * @param array $conditions Return data for ApiBase::getConditionalRequestData
490 * @param int $status Expected response status
491 * @param array $options Array of options:
492 * post => true Request is a POST
493 * cdn => true CDN is enabled ($wgUseCdn)
495 public function testCheckConditionalRequestHeaders(
496 $headers, $conditions, $status, $options = []
498 $request = new FauxRequest(
499 [ 'action' => 'query', 'meta' => 'siteinfo' ],
500 !empty( $options['post'] )
502 $request->setHeaders( $headers );
503 $request->response()->statusHeader( 200 ); // Why doesn't it default?
505 $context = $this->apiContext
->newTestContext( $request, null );
506 $api = new ApiMain( $context );
507 $priv = TestingAccessWrapper
::newFromObject( $api );
508 $priv->mInternalMode
= false;
510 if ( !empty( $options['cdn'] ) ) {
511 $this->setMwGlobals( 'wgUseCdn', true );
514 // Can't do this in TestSetup.php because Setup.php will override it
515 $this->setMwGlobals( 'wgCacheEpoch', '20030516000000' );
517 $module = $this->getMockBuilder( ApiBase
::class )
518 ->setConstructorArgs( [ $api, 'mock' ] )
519 ->setMethods( [ 'getConditionalRequestData' ] )
520 ->getMockForAbstractClass();
521 $module->expects( $this->any() )
522 ->method( 'getConditionalRequestData' )
523 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
524 return $conditions[$condition] ??
null;
527 $ret = $priv->checkConditionalRequestHeaders( $module );
529 $this->assertSame( $status, $request->response()->getStatusCode() );
530 $this->assertSame( $status === 200, $ret );
533 public static function provideCheckConditionalRequestHeaders() {
538 // Non-existing from module is ignored
539 'If-None-Match' => [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
540 'If-Modified-Since' =>
541 [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
544 'No headers' => [ [], [ 'etag' => '""', 'last-modified' => '20150815000000', ], 200 ],
546 // Basic If-None-Match
547 'If-None-Match with matching etag' =>
548 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
549 'If-None-Match with non-matching etag' =>
550 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
551 'Strong If-None-Match with weak matching etag' =>
552 [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
553 'Weak If-None-Match with strong matching etag' =>
554 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
555 'Weak If-None-Match with weak matching etag' =>
556 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
558 // Pointless for GET, but supported
559 'If-None-Match: *' => [ [ 'If-None-Match' => '*' ], [], 304 ],
561 // Basic If-Modified-Since
562 'If-Modified-Since, modified one second earlier' =>
563 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
564 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
565 'If-Modified-Since, modified now' =>
566 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
567 [ 'last-modified' => wfTimestamp( TS_MW
, $now ) ], 304 ],
568 'If-Modified-Since, modified one second later' =>
569 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
570 [ 'last-modified' => wfTimestamp( TS_MW
, $now +
1 ) ], 200 ],
572 // If-Modified-Since ignored when If-None-Match is given too
573 'Non-matching If-None-Match and matching If-Modified-Since' =>
574 [ [ 'If-None-Match' => '""',
575 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
576 [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
577 'Non-matching If-None-Match and matching If-Modified-Since with no ETag' =>
580 'If-None-Match' => '""',
581 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now )
583 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ],
588 'Matching If-None-Match with POST' =>
589 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200,
590 [ 'post' => true ] ],
591 'Matching If-Modified-Since with POST' =>
592 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
593 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200,
594 [ 'post' => true ] ],
596 // Other date formats allowed by the RFC
597 'If-Modified-Since with alternate date format 1' =>
598 [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
599 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
600 'If-Modified-Since with alternate date format 2' =>
601 [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
602 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
604 // Old browser extension to HTTP/1.0
605 'If-Modified-Since with length' =>
606 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) . '; length=123' ],
607 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
609 // Invalid date formats should be ignored
610 'If-Modified-Since with invalid date format' =>
611 [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
612 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
613 'If-Modified-Since with entirely unparseable date' =>
614 [ [ 'If-Modified-Since' => 'a potato' ],
615 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
617 // Anything before $wgCdnMaxAge seconds ago should be considered
619 'If-Modified-Since with CDN post-expiry' =>
620 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now - $wgCdnMaxAge * 2 ) ],
621 [ 'last-modified' => wfTimestamp( TS_MW
, $now - $wgCdnMaxAge * 3 ) ],
622 200, [ 'cdn' => true ] ],
623 'If-Modified-Since with CDN pre-expiry' =>
624 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now - $wgCdnMaxAge / 2 ) ],
625 [ 'last-modified' => wfTimestamp( TS_MW
, $now - $wgCdnMaxAge * 3 ) ],
626 304, [ 'cdn' => true ] ],
631 * Test conditional headers output
632 * @dataProvider provideConditionalRequestHeadersOutput
633 * @param array $conditions Return data for ApiBase::getConditionalRequestData
634 * @param array $headers Expected output headers
635 * @param bool $isError $isError flag
636 * @param bool $post Request is a POST
638 public function testConditionalRequestHeadersOutput(
639 $conditions, $headers, $isError = false, $post = false
641 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
642 $response = $request->response();
644 $api = new ApiMain( $request );
645 $priv = TestingAccessWrapper
::newFromObject( $api );
646 $priv->mInternalMode
= false;
648 $module = $this->getMockBuilder( ApiBase
::class )
649 ->setConstructorArgs( [ $api, 'mock' ] )
650 ->setMethods( [ 'getConditionalRequestData' ] )
651 ->getMockForAbstractClass();
652 $module->expects( $this->any() )
653 ->method( 'getConditionalRequestData' )
654 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
655 return $conditions[$condition] ??
null;
657 $priv->mModule
= $module;
659 $priv->sendCacheHeaders( $isError );
661 foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
663 $headers[$header] ??
null,
664 $response->getHeader( $header ),
670 public static function provideConditionalRequestHeadersOutput() {
677 [ 'etag' => '"foo"' ],
678 [ 'ETag' => '"foo"' ]
681 [ 'last-modified' => '20150818000102' ],
682 [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
685 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
686 [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
689 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
694 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
702 public function testCheckExecutePermissionsReadProhibited() {
703 $this->setExpectedException( ApiUsageException
::class,
704 'You need read permission to use this module.' );
706 $this->setGroupPermissions( '*', 'read', false );
708 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
712 public function testCheckExecutePermissionWriteDisabled() {
713 $this->setExpectedException( ApiUsageException
::class,
714 'Editing of this wiki through the API is disabled. Make sure the ' .
715 '"$wgEnableWriteAPI=true;" statement is included in the wiki\'s ' .
716 '"LocalSettings.php" file.' );
717 $main = new ApiMain( new FauxRequest( [
719 'title' => 'Some page',
720 'text' => 'Some text',
726 public function testCheckExecutePermissionWriteApiProhibited() {
727 $this->setExpectedException( ApiUsageException
::class,
728 "You're not allowed to edit this wiki through the API." );
729 $this->setGroupPermissions( '*', 'writeapi', false );
731 $main = new ApiMain( new FauxRequest( [
733 'title' => 'Some page',
734 'text' => 'Some text',
736 ] ), /* enableWrite = */ true );
740 public function testCheckExecutePermissionPromiseNonWrite() {
741 $this->setExpectedException( ApiUsageException
::class,
742 'The "Promise-Non-Write-API-Action" HTTP header cannot be sent ' .
743 'to write-mode API modules.' );
745 $req = new FauxRequest( [
747 'title' => 'Some page',
748 'text' => 'Some text',
751 $req->setHeaders( [ 'Promise-Non-Write-API-Action' => '1' ] );
752 $main = new ApiMain( $req, /* enableWrite = */ true );
756 public function testCheckExecutePermissionHookAbort() {
757 $this->setExpectedException( ApiUsageException
::class, 'Main Page' );
759 $this->setTemporaryHook( 'ApiCheckCanExecute', function ( $unused1, $unused2, &$message ) {
760 $message = 'mainpage';
764 $main = new ApiMain( new FauxRequest( [
766 'title' => 'Some page',
767 'text' => 'Some text',
769 ] ), /* enableWrite = */ true );
773 public function testGetValUnsupportedArray() {
774 $main = new ApiMain( new FauxRequest( [
776 'meta' => 'siteinfo',
777 'siprop' => [ 'general', 'namespaces' ],
779 $this->assertSame( 'myDefault', $main->getVal( 'siprop', 'myDefault' ) );
781 $this->assertSame( 'Parameter "siprop" uses unsupported PHP array syntax.',
782 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
785 public function testReportUnusedParams() {
786 $main = new ApiMain( new FauxRequest( [
788 'meta' => 'siteinfo',
789 'unusedparam' => 'unusedval',
790 'anotherunusedparam' => 'anotherval',
793 $this->assertSame( 'Unrecognized parameters: unusedparam, anotherunusedparam.',
794 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
797 public function testLacksSameOriginSecurity() {
799 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
800 $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
804 new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
806 $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
809 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
810 $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
811 $main = new ApiMain( $request );
812 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
815 $this->mergeMwGlobalArrayValue( 'wgHooks', [
816 'RequestHasSameOriginSecurity' => [ function () {
820 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
821 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
825 * Test proper creation of the ApiErrorFormatter
827 * @dataProvider provideApiErrorFormatterCreation
828 * @param array $request Request parameters
829 * @param array $expect Expected data
830 * - uselang: ApiMain language
831 * - class: ApiErrorFormatter class
832 * - lang: ApiErrorFormatter language
833 * - format: ApiErrorFormatter format
834 * - usedb: ApiErrorFormatter use-database flag
836 public function testApiErrorFormatterCreation( array $request, array $expect ) {
837 $context = new RequestContext();
838 $context->setRequest( new FauxRequest( $request ) );
839 $context->setLanguage( 'ru' );
841 $main = new ApiMain( $context );
842 $formatter = $main->getErrorFormatter();
843 $wrappedFormatter = TestingAccessWrapper
::newFromObject( $formatter );
845 $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
846 $this->assertInstanceOf( $expect['class'], $formatter );
847 $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
848 $this->assertSame( $expect['format'], $wrappedFormatter->format
);
849 $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB
);
852 public static function provideApiErrorFormatterCreation() {
854 'Default (BC)' => [ [], [
856 'class' => ApiErrorFormatter_BackCompat
::class,
861 'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
863 'class' => ApiErrorFormatter_BackCompat
::class,
868 'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
870 'class' => ApiErrorFormatter_BackCompat
::class,
875 'Basic' => [ [ 'errorformat' => 'wikitext' ], [
877 'class' => ApiErrorFormatter
::class,
879 'format' => 'wikitext',
882 'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
884 'class' => ApiErrorFormatter
::class,
886 'format' => 'plaintext',
889 'Explicitly follows uselang' => [
890 [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
893 'class' => ApiErrorFormatter
::class,
895 'format' => 'plaintext',
899 'uselang=content' => [
900 [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
903 'class' => ApiErrorFormatter
::class,
905 'format' => 'plaintext',
909 'errorlang=content' => [
910 [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
913 'class' => ApiErrorFormatter
::class,
915 'format' => 'plaintext',
919 'Explicit parameters' => [
920 [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
923 'class' => ApiErrorFormatter
::class,
929 'Explicit parameters override uselang' => [
930 [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
933 'class' => ApiErrorFormatter
::class,
939 'Bogus language doesn\'t explode' => [
940 [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
943 'class' => ApiErrorFormatter
::class,
949 'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
951 'class' => ApiErrorFormatter_BackCompat
::class,
960 * @dataProvider provideExceptionErrors
961 * @param Exception $exception
962 * @param array $expectReturn
963 * @param array $expectResult
965 public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
966 $context = new RequestContext();
967 $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
968 $context->setLanguage( 'en' );
969 $context->setConfig( new MultiConfig( [
971 'ShowHostnames' => true, 'ShowExceptionDetails' => true,
973 $context->getConfig()
976 $main = new ApiMain( $context );
977 $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
978 $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
980 $ret = TestingAccessWrapper
::newFromObject( $main )->substituteResultWithError( $error );
981 $this->assertSame( $expectReturn, $ret );
983 // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
984 // so let's try ->assertEquals().
987 $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
991 // Not static so $this can be used
992 public function provideExceptionErrors() {
993 $reqId = WebRequest
::getRequestId();
994 $doclink = wfExpandUrl( wfScript( 'api' ) );
996 $ex = new InvalidArgumentException( 'Random exception' );
997 $trace = wfMessage( 'api-exception-trace',
1001 MWExceptionHandler
::getRedactedTraceAsString( $ex )
1002 )->inLanguage( 'en' )->useDatabase( false )->text();
1004 $dbex = new DBQueryError(
1005 $this->createMock( \Wikimedia\Rdbms\IDatabase
::class ),
1006 'error', 1234, 'SELECT 1', __METHOD__
);
1007 $dbtrace = wfMessage( 'api-exception-trace',
1011 MWExceptionHandler
::getRedactedTraceAsString( $dbex )
1012 )->inLanguage( 'en' )->useDatabase( false )->text();
1014 // The specific exception doesn't matter, as long as it's namespaced.
1015 $nsex = new MediaWiki\
ShellDisabledError();
1016 $nstrace = wfMessage( 'api-exception-trace',
1020 MWExceptionHandler
::getRedactedTraceAsString( $nsex )
1021 )->inLanguage( 'en' )->useDatabase( false )->text();
1023 $apiEx1 = new ApiUsageException( null,
1024 StatusValue
::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
1025 TestingAccessWrapper
::newFromObject( $apiEx1 )->modulePath
= 'foo+bar';
1026 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
1027 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
1028 $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
1030 $badMsg = $this->getMockBuilder( ApiRawMessage
::class )
1031 ->setConstructorArgs( [ 'An error', 'ignored' ] )
1032 ->setMethods( [ 'getApiCode' ] )
1034 $badMsg->method( 'getApiCode' )->willReturn( "bad\nvalue" );
1035 $apiEx2 = new ApiUsageException( null, StatusValue
::newFatal( $badMsg ) );
1040 [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
1043 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1046 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1048 'code' => 'internal_api_error_InvalidArgumentException',
1049 'text' => "[$reqId] Exception caught: Random exception",
1051 'errorclass' => InvalidArgumentException
::class,
1056 'servedby' => wfHostname(),
1061 [ 'existing-error', 'internal_api_error_DBQueryError' ],
1064 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1067 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1069 'code' => 'internal_api_error_DBQueryError',
1070 'text' => "[$reqId] Exception caught: A database query error has occurred. " .
1071 "This may indicate a bug in the software.",
1073 'errorclass' => DBQueryError
::class,
1077 'trace' => $dbtrace,
1078 'servedby' => wfHostname(),
1083 [ 'existing-error', 'internal_api_error_MediaWiki\ShellDisabledError' ],
1086 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1089 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1091 'code' => 'internal_api_error_MediaWiki\ShellDisabledError',
1092 'text' => "[$reqId] Exception caught: " . $nsex->getMessage(),
1094 'errorclass' => MediaWiki\ShellDisabledError
::class,
1098 'trace' => $nstrace,
1099 'servedby' => wfHostname(),
1104 [ 'existing-error', 'sv-error1', 'sv-error2' ],
1107 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1108 [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
1109 [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
1112 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1113 [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
1114 [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
1116 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1117 "list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> " .
1118 "for notice of API deprecations and breaking changes.",
1119 'servedby' => wfHostname(),
1124 [ 'existing-error', '<invalid-code>' ],
1127 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1130 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1131 [ 'code' => "bad\nvalue", 'text' => 'An error' ],
1133 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1134 "list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> " .
1135 "for notice of API deprecations and breaking changes.",
1136 'servedby' => wfHostname(),
1142 public function testPrinterParameterValidationError() {
1143 $api = $this->getNonInternalApiMain( [
1144 'action' => 'query', 'meta' => 'siteinfo', 'format' => 'json', 'formatversion' => 'bogus',
1149 $txt = ob_get_clean();
1151 // Test that the actual output is valid JSON, not just the format of the ApiResult.
1152 $data = FormatJson
::decode( $txt, true );
1153 $this->assertInternalType( 'array', $data );
1154 $this->assertArrayHasKey( 'error', $data );
1155 $this->assertArrayHasKey( 'code', $data['error'] );
1156 $this->assertSame( 'unknown_formatversion', $data['error']['code'] );