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 );
153 $wrappedApi = TestingAccessWrapper
::newFromObject( new ApiMain() );
154 $wrappedApi->setCacheMode( 'public' );
155 $this->assertSame( 'private', $wrappedApi->mCacheMode
);
156 $wrappedApi->setCacheMode( 'anon-public-user-private' );
157 $this->assertSame( 'private', $wrappedApi->mCacheMode
);
160 public function testAddRequestedFieldsRequestId() {
161 $req = new FauxRequest( [
163 'meta' => 'siteinfo',
164 'requestid' => '123456',
166 $api = new ApiMain( $req );
168 $this->assertSame( '123456', $api->getResult()->getResultData()['requestid'] );
171 public function testAddRequestedFieldsCurTimestamp() {
172 $req = new FauxRequest( [
174 'meta' => 'siteinfo',
175 'curtimestamp' => '',
177 $api = new ApiMain( $req );
179 $timestamp = $api->getResult()->getResultData()['curtimestamp'];
180 $this->assertLessThanOrEqual( 1, abs( strtotime( $timestamp ) - time() ) );
183 public function testAddRequestedFieldsResponseLangInfo() {
184 $req = new FauxRequest( [
186 'meta' => 'siteinfo',
187 // errorlang is ignored if errorformat is not specified
188 'errorformat' => 'plaintext',
191 'responselanginfo' => '',
193 $api = new ApiMain( $req );
195 $data = $api->getResult()->getResultData();
196 $this->assertSame( 'fr', $data['uselang'] );
197 $this->assertSame( 'ja', $data['errorlang'] );
200 public function testSetupModuleUnknown() {
201 $this->setExpectedException( ApiUsageException
::class,
202 'Unrecognized value for parameter "action": unknownaction.' );
204 $req = new FauxRequest( [ 'action' => 'unknownaction' ] );
205 $api = new ApiMain( $req );
209 public function testSetupModuleNoTokenProvided() {
210 $this->setExpectedException( ApiUsageException
::class,
211 'The "token" parameter must be set.' );
213 $req = new FauxRequest( [
215 'title' => 'New page',
216 'text' => 'Some text',
218 $api = new ApiMain( $req );
222 public function testSetupModuleInvalidTokenProvided() {
223 $this->setExpectedException( ApiUsageException
::class, 'Invalid CSRF token.' );
225 $req = new FauxRequest( [
227 'title' => 'New page',
228 'text' => 'Some text',
229 'token' => "This isn't a real token!",
231 $api = new ApiMain( $req );
235 public function testSetupModuleNeedsTokenTrue() {
236 $this->setExpectedException( MWException
::class,
237 "Module 'testmodule' must be updated for the new token handling. " .
238 "See documentation for ApiBase::needsToken for details." );
240 $mock = $this->createMock( ApiBase
::class );
241 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
242 $mock->method( 'needsToken' )->willReturn( true );
244 $api = new ApiMain( new FauxRequest( [ 'action' => 'testmodule' ] ) );
245 $api->getModuleManager()->addModule( 'testmodule', 'action', [
246 'class' => get_class( $mock ),
247 'factory' => 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', [
265 'class' => get_class( $mock ),
266 'factory' => function () use ( $mock ) {
273 public function testCheckMaxLagFailed() {
274 // It's hard to mock the LoadBalancer properly, so instead we'll mock
275 // checkMaxLag (which is tested directly in other tests below).
276 $req = new FauxRequest( [
278 'meta' => 'siteinfo',
281 $mock = $this->getMockBuilder( ApiMain
::class )
282 ->setConstructorArgs( [ $req ] )
283 ->setMethods( [ 'checkMaxLag' ] )
285 $mock->method( 'checkMaxLag' )->willReturn( false );
289 $this->assertArrayNotHasKey( 'query', $mock->getResult()->getResultData() );
292 public function testCheckConditionalRequestHeadersFailed() {
293 // The detailed checking of all cases of checkConditionalRequestHeaders
294 // is below in testCheckConditionalRequestHeaders(), which calls the
295 // method directly. Here we just check that it will stop execution if
299 $this->setMwGlobals( 'wgCacheEpoch', '20030516000000' );
301 $mock = $this->createMock( ApiBase
::class );
302 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
303 $mock->method( 'getConditionalRequestData' )
304 ->willReturn( wfTimestamp( TS_MW
, $now - 3600 ) );
305 $mock->expects( $this->exactly( 0 ) )->method( 'execute' );
307 $req = new FauxRequest( [
308 'action' => 'testmodule',
310 $req->setHeader( 'If-Modified-Since', wfTimestamp( TS_RFC2822
, $now - 3600 ) );
311 $req->setRequestURL( "http://localhost" );
313 $api = new ApiMain( $req );
314 $api->getModuleManager()->addModule( 'testmodule', 'action', [
315 'class' => get_class( $mock ),
316 'factory' => function () use ( $mock ) {
321 $wrapper = TestingAccessWrapper
::newFromObject( $api );
322 $wrapper->mInternalMode
= false;
329 private function doTestCheckMaxLag( $lag ) {
330 $mockLB = $this->getMockBuilder( LoadBalancer
::class )
331 ->disableOriginalConstructor()
332 ->setMethods( [ 'getMaxLag', '__destruct' ] )
334 $mockLB->method( 'getMaxLag' )->willReturn( [ 'somehost', $lag ] );
335 $this->setService( 'DBLoadBalancer', $mockLB );
337 $req = new FauxRequest();
339 $api = new ApiMain( $req );
340 $wrapper = TestingAccessWrapper
::newFromObject( $api );
342 $mockModule = $this->createMock( ApiBase
::class );
343 $mockModule->method( 'shouldCheckMaxLag' )->willReturn( true );
346 $wrapper->checkMaxLag( $mockModule, [ 'maxlag' => 3 ] );
349 $this->assertSame( '5', $req->response()->getHeader( 'Retry-After' ) );
350 $this->assertSame( (string)$lag, $req->response()->getHeader( 'X-Database-Lag' ) );
355 public function testCheckMaxLagOkay() {
356 $this->doTestCheckMaxLag( 3 );
358 // No exception, we're happy
359 $this->assertTrue( true );
362 public function testCheckMaxLagExceeded() {
363 $this->setExpectedException( ApiUsageException
::class,
364 'Waiting for a database server: 4 seconds lagged.' );
366 $this->setMwGlobals( 'wgShowHostnames', false );
368 $this->doTestCheckMaxLag( 4 );
371 public function testCheckMaxLagExceededWithHostNames() {
372 $this->setExpectedException( ApiUsageException
::class,
373 'Waiting for somehost: 4 seconds lagged.' );
375 $this->setMwGlobals( 'wgShowHostnames', true );
377 $this->doTestCheckMaxLag( 4 );
380 public static function provideAssert() {
382 [ false, [], 'user', 'assertuserfailed' ],
383 [ true, [], 'user', false ],
384 [ true, [], 'bot', 'assertbotfailed' ],
385 [ true, [ 'bot' ], 'user', false ],
386 [ true, [ 'bot' ], 'bot', false ],
391 * Tests the assert={user|bot} functionality
393 * @dataProvider provideAssert
394 * @param bool $registered
395 * @param array $rights
396 * @param string $assert
397 * @param string|bool $error False if no error expected
399 public function testAssert( $registered, $rights, $assert, $error ) {
401 $user = $this->getMutableTestUser()->getUser();
402 $user->load(); // load before setting mRights
406 $this->overrideUserPermissions( $user, $rights );
408 $this->doApiRequest( [
411 ], null, null, $user );
412 $this->assertFalse( $error ); // That no error was expected
413 } catch ( ApiUsageException
$e ) {
414 $this->assertTrue( self
::apiExceptionHasCode( $e, $error ),
415 "Error '{$e->getMessage()}' matched expected '$error'" );
420 * Tests the assertuser= functionality
422 public function testAssertUser() {
423 $user = $this->getTestUser()->getUser();
424 $this->doApiRequest( [
426 'assertuser' => $user->getName(),
427 ], null, null, $user );
430 $this->doApiRequest( [
432 'assertuser' => $user->getName() . 'X',
433 ], null, null, $user );
434 $this->fail( 'Expected exception not thrown' );
435 } catch ( ApiUsageException
$e ) {
436 $this->assertTrue( self
::apiExceptionHasCode( $e, 'assertnameduserfailed' ) );
441 * Test that 'assert' is processed before module errors
443 public function testAssertBeforeModule() {
444 // Sanity check that the query without assert throws too-many-titles
446 $this->doApiRequest( [
448 'titles' => implode( '|', range( 1, ApiBase
::LIMIT_SML1 +
1 ) ),
449 ], null, null, new User
);
450 $this->fail( 'Expected exception not thrown' );
451 } catch ( ApiUsageException
$e ) {
452 $this->assertTrue( self
::apiExceptionHasCode( $e, 'too-many-titles' ), 'sanity check' );
455 // Now test that the assert happens first
457 $this->doApiRequest( [
459 'titles' => implode( '|', range( 1, ApiBase
::LIMIT_SML1 +
1 ) ),
461 ], null, null, new User
);
462 $this->fail( 'Expected exception not thrown' );
463 } catch ( ApiUsageException
$e ) {
464 $this->assertTrue( self
::apiExceptionHasCode( $e, 'assertuserfailed' ),
465 "Error '{$e->getMessage()}' matched expected 'assertuserfailed'" );
470 * Test if all classes in the main module manager exists
472 public function testClassNamesInModuleManager() {
474 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
476 $modules = $api->getModuleManager()->getNamesWithClasses();
478 foreach ( $modules as $name => $class ) {
480 class_exists( $class ),
481 'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
487 * Test HTTP precondition headers
489 * @dataProvider provideCheckConditionalRequestHeaders
490 * @param array $headers HTTP headers
491 * @param array $conditions Return data for ApiBase::getConditionalRequestData
492 * @param int $status Expected response status
493 * @param array $options Array of options:
494 * post => true Request is a POST
495 * cdn => true CDN is enabled ($wgUseCdn)
497 public function testCheckConditionalRequestHeaders(
498 $headers, $conditions, $status, $options = []
500 $request = new FauxRequest(
501 [ 'action' => 'query', 'meta' => 'siteinfo' ],
502 !empty( $options['post'] )
504 $request->setHeaders( $headers );
505 $request->response()->statusHeader( 200 ); // Why doesn't it default?
507 $context = $this->apiContext
->newTestContext( $request, null );
508 $api = new ApiMain( $context );
509 $priv = TestingAccessWrapper
::newFromObject( $api );
510 $priv->mInternalMode
= false;
512 if ( !empty( $options['cdn'] ) ) {
513 $this->setMwGlobals( 'wgUseCdn', true );
516 // Can't do this in TestSetup.php because Setup.php will override it
517 $this->setMwGlobals( 'wgCacheEpoch', '20030516000000' );
519 $module = $this->getMockBuilder( ApiBase
::class )
520 ->setConstructorArgs( [ $api, 'mock' ] )
521 ->setMethods( [ 'getConditionalRequestData' ] )
522 ->getMockForAbstractClass();
523 $module->expects( $this->any() )
524 ->method( 'getConditionalRequestData' )
525 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
526 return $conditions[$condition] ??
null;
529 $ret = $priv->checkConditionalRequestHeaders( $module );
531 $this->assertSame( $status, $request->response()->getStatusCode() );
532 $this->assertSame( $status === 200, $ret );
535 public static function provideCheckConditionalRequestHeaders() {
540 // Non-existing from module is ignored
541 'If-None-Match' => [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
542 'If-Modified-Since' =>
543 [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
546 'No headers' => [ [], [ 'etag' => '""', 'last-modified' => '20150815000000', ], 200 ],
548 // Basic If-None-Match
549 'If-None-Match with matching etag' =>
550 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
551 'If-None-Match with non-matching etag' =>
552 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
553 'Strong If-None-Match with weak matching etag' =>
554 [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
555 'Weak If-None-Match with strong matching etag' =>
556 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
557 'Weak If-None-Match with weak matching etag' =>
558 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
560 // Pointless for GET, but supported
561 'If-None-Match: *' => [ [ 'If-None-Match' => '*' ], [], 304 ],
563 // Basic If-Modified-Since
564 'If-Modified-Since, modified one second earlier' =>
565 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
566 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
567 'If-Modified-Since, modified now' =>
568 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
569 [ 'last-modified' => wfTimestamp( TS_MW
, $now ) ], 304 ],
570 'If-Modified-Since, modified one second later' =>
571 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
572 [ 'last-modified' => wfTimestamp( TS_MW
, $now +
1 ) ], 200 ],
574 // If-Modified-Since ignored when If-None-Match is given too
575 'Non-matching If-None-Match and matching If-Modified-Since' =>
576 [ [ 'If-None-Match' => '""',
577 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
578 [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
579 'Non-matching If-None-Match and matching If-Modified-Since with no ETag' =>
582 'If-None-Match' => '""',
583 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now )
585 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ],
590 'Matching If-None-Match with POST' =>
591 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200,
592 [ 'post' => true ] ],
593 'Matching If-Modified-Since with POST' =>
594 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) ],
595 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200,
596 [ 'post' => true ] ],
598 // Other date formats allowed by the RFC
599 'If-Modified-Since with alternate date format 1' =>
600 [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
601 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
602 'If-Modified-Since with alternate date format 2' =>
603 [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
604 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
606 // Old browser extension to HTTP/1.0
607 'If-Modified-Since with length' =>
608 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now ) . '; length=123' ],
609 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 304 ],
611 // Invalid date formats should be ignored
612 'If-Modified-Since with invalid date format' =>
613 [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
614 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
615 'If-Modified-Since with entirely unparseable date' =>
616 [ [ 'If-Modified-Since' => 'a potato' ],
617 [ 'last-modified' => wfTimestamp( TS_MW
, $now - 1 ) ], 200 ],
619 // Anything before $wgCdnMaxAge seconds ago should be considered
621 'If-Modified-Since with CDN post-expiry' =>
622 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now - $wgCdnMaxAge * 2 ) ],
623 [ 'last-modified' => wfTimestamp( TS_MW
, $now - $wgCdnMaxAge * 3 ) ],
624 200, [ 'cdn' => true ] ],
625 'If-Modified-Since with CDN pre-expiry' =>
626 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822
, $now - $wgCdnMaxAge / 2 ) ],
627 [ 'last-modified' => wfTimestamp( TS_MW
, $now - $wgCdnMaxAge * 3 ) ],
628 304, [ 'cdn' => true ] ],
633 * Test conditional headers output
634 * @dataProvider provideConditionalRequestHeadersOutput
635 * @param array $conditions Return data for ApiBase::getConditionalRequestData
636 * @param array $headers Expected output headers
637 * @param bool $isError $isError flag
638 * @param bool $post Request is a POST
640 public function testConditionalRequestHeadersOutput(
641 $conditions, $headers, $isError = false, $post = false
643 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
644 $response = $request->response();
646 $api = new ApiMain( $request );
647 $priv = TestingAccessWrapper
::newFromObject( $api );
648 $priv->mInternalMode
= false;
650 $module = $this->getMockBuilder( ApiBase
::class )
651 ->setConstructorArgs( [ $api, 'mock' ] )
652 ->setMethods( [ 'getConditionalRequestData' ] )
653 ->getMockForAbstractClass();
654 $module->expects( $this->any() )
655 ->method( 'getConditionalRequestData' )
656 ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
657 return $conditions[$condition] ??
null;
659 $priv->mModule
= $module;
661 $priv->sendCacheHeaders( $isError );
663 foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
665 $headers[$header] ??
null,
666 $response->getHeader( $header ),
672 public static function provideConditionalRequestHeadersOutput() {
679 [ 'etag' => '"foo"' ],
680 [ 'ETag' => '"foo"' ]
683 [ 'last-modified' => '20150818000102' ],
684 [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
687 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
688 [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
691 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
696 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
704 public function testCheckExecutePermissionsReadProhibited() {
705 $this->setExpectedException( ApiUsageException
::class,
706 'You need read permission to use this module.' );
708 $this->setGroupPermissions( '*', 'read', false );
710 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
714 public function testCheckExecutePermissionWriteDisabled() {
715 $this->setExpectedException( ApiUsageException
::class,
716 'Editing of this wiki through the API is disabled. Make sure the ' .
717 '"$wgEnableWriteAPI=true;" statement is included in the wiki\'s ' .
718 '"LocalSettings.php" file.' );
719 $main = new ApiMain( new FauxRequest( [
721 'title' => 'Some page',
722 'text' => 'Some text',
728 public function testCheckExecutePermissionWriteApiProhibited() {
729 $this->setExpectedException( ApiUsageException
::class,
730 "You're not allowed to edit this wiki through the API." );
731 $this->setGroupPermissions( '*', 'writeapi', false );
733 $main = new ApiMain( new FauxRequest( [
735 'title' => 'Some page',
736 'text' => 'Some text',
738 ] ), /* enableWrite = */ true );
742 public function testCheckExecutePermissionPromiseNonWrite() {
743 $this->setExpectedException( ApiUsageException
::class,
744 'The "Promise-Non-Write-API-Action" HTTP header cannot be sent ' .
745 'to write-mode API modules.' );
747 $req = new FauxRequest( [
749 'title' => 'Some page',
750 'text' => 'Some text',
753 $req->setHeaders( [ 'Promise-Non-Write-API-Action' => '1' ] );
754 $main = new ApiMain( $req, /* enableWrite = */ true );
758 public function testCheckExecutePermissionHookAbort() {
759 $this->setExpectedException( ApiUsageException
::class, 'Main Page' );
761 $this->setTemporaryHook( 'ApiCheckCanExecute', function ( $unused1, $unused2, &$message ) {
762 $message = 'mainpage';
766 $main = new ApiMain( new FauxRequest( [
768 'title' => 'Some page',
769 'text' => 'Some text',
771 ] ), /* enableWrite = */ true );
775 public function testGetValUnsupportedArray() {
776 $main = new ApiMain( new FauxRequest( [
778 'meta' => 'siteinfo',
779 'siprop' => [ 'general', 'namespaces' ],
781 $this->assertSame( 'myDefault', $main->getVal( 'siprop', 'myDefault' ) );
783 $this->assertSame( 'Parameter "siprop" uses unsupported PHP array syntax.',
784 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
787 public function testReportUnusedParams() {
788 $main = new ApiMain( new FauxRequest( [
790 'meta' => 'siteinfo',
791 'unusedparam' => 'unusedval',
792 'anotherunusedparam' => 'anotherval',
795 $this->assertSame( 'Unrecognized parameters: unusedparam, anotherunusedparam.',
796 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
799 public function testLacksSameOriginSecurity() {
801 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
802 $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
806 new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
808 $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
811 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
812 $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
813 $main = new ApiMain( $request );
814 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
817 $this->mergeMwGlobalArrayValue( 'wgHooks', [
818 'RequestHasSameOriginSecurity' => [ function () {
822 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
823 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
827 * Test proper creation of the ApiErrorFormatter
829 * @dataProvider provideApiErrorFormatterCreation
830 * @param array $request Request parameters
831 * @param array $expect Expected data
832 * - uselang: ApiMain language
833 * - class: ApiErrorFormatter class
834 * - lang: ApiErrorFormatter language
835 * - format: ApiErrorFormatter format
836 * - usedb: ApiErrorFormatter use-database flag
838 public function testApiErrorFormatterCreation( array $request, array $expect ) {
839 $context = new RequestContext();
840 $context->setRequest( new FauxRequest( $request ) );
841 $context->setLanguage( 'ru' );
843 $main = new ApiMain( $context );
844 $formatter = $main->getErrorFormatter();
845 $wrappedFormatter = TestingAccessWrapper
::newFromObject( $formatter );
847 $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
848 $this->assertInstanceOf( $expect['class'], $formatter );
849 $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
850 $this->assertSame( $expect['format'], $wrappedFormatter->format
);
851 $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB
);
854 public static function provideApiErrorFormatterCreation() {
856 'Default (BC)' => [ [], [
858 'class' => ApiErrorFormatter_BackCompat
::class,
863 'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
865 'class' => ApiErrorFormatter_BackCompat
::class,
870 'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
872 'class' => ApiErrorFormatter_BackCompat
::class,
877 'Basic' => [ [ 'errorformat' => 'wikitext' ], [
879 'class' => ApiErrorFormatter
::class,
881 'format' => 'wikitext',
884 'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
886 'class' => ApiErrorFormatter
::class,
888 'format' => 'plaintext',
891 'Explicitly follows uselang' => [
892 [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
895 'class' => ApiErrorFormatter
::class,
897 'format' => 'plaintext',
901 'uselang=content' => [
902 [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
905 'class' => ApiErrorFormatter
::class,
907 'format' => 'plaintext',
911 'errorlang=content' => [
912 [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
915 'class' => ApiErrorFormatter
::class,
917 'format' => 'plaintext',
921 'Explicit parameters' => [
922 [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
925 'class' => ApiErrorFormatter
::class,
931 'Explicit parameters override uselang' => [
932 [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
935 'class' => ApiErrorFormatter
::class,
941 'Bogus language doesn\'t explode' => [
942 [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
945 'class' => ApiErrorFormatter
::class,
951 'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
953 'class' => ApiErrorFormatter_BackCompat
::class,
962 * @dataProvider provideExceptionErrors
963 * @param Exception $exception
964 * @param array $expectReturn
965 * @param array $expectResult
967 public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
968 $context = new RequestContext();
969 $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
970 $context->setLanguage( 'en' );
971 $context->setConfig( new MultiConfig( [
973 'ShowHostnames' => true, 'ShowExceptionDetails' => true,
975 $context->getConfig()
978 $main = new ApiMain( $context );
979 $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
980 $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
982 $ret = TestingAccessWrapper
::newFromObject( $main )->substituteResultWithError( $error );
983 $this->assertSame( $expectReturn, $ret );
985 // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
986 // so let's try ->assertEquals().
989 $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
993 // Not static so $this can be used
994 public function provideExceptionErrors() {
995 $reqId = WebRequest
::getRequestId();
996 $doclink = wfExpandUrl( wfScript( 'api' ) );
998 $ex = new InvalidArgumentException( 'Random exception' );
999 $trace = wfMessage( 'api-exception-trace',
1003 MWExceptionHandler
::getRedactedTraceAsString( $ex )
1004 )->inLanguage( 'en' )->useDatabase( false )->text();
1006 $dbex = new DBQueryError(
1007 $this->createMock( \Wikimedia\Rdbms\IDatabase
::class ),
1008 'error', 1234, 'SELECT 1', __METHOD__
);
1009 $dbtrace = wfMessage( 'api-exception-trace',
1013 MWExceptionHandler
::getRedactedTraceAsString( $dbex )
1014 )->inLanguage( 'en' )->useDatabase( false )->text();
1016 // The specific exception doesn't matter, as long as it's namespaced.
1017 $nsex = new MediaWiki\
ShellDisabledError();
1018 $nstrace = wfMessage( 'api-exception-trace',
1022 MWExceptionHandler
::getRedactedTraceAsString( $nsex )
1023 )->inLanguage( 'en' )->useDatabase( false )->text();
1025 $apiEx1 = new ApiUsageException( null,
1026 StatusValue
::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
1027 TestingAccessWrapper
::newFromObject( $apiEx1 )->modulePath
= 'foo+bar';
1028 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
1029 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
1030 $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
1032 $badMsg = $this->getMockBuilder( ApiRawMessage
::class )
1033 ->setConstructorArgs( [ 'An error', 'ignored' ] )
1034 ->setMethods( [ 'getApiCode' ] )
1036 $badMsg->method( 'getApiCode' )->willReturn( "bad\nvalue" );
1037 $apiEx2 = new ApiUsageException( null, StatusValue
::newFatal( $badMsg ) );
1042 [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
1045 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1048 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1050 'code' => 'internal_api_error_InvalidArgumentException',
1051 'text' => "[$reqId] Exception caught: Random exception",
1053 'errorclass' => InvalidArgumentException
::class,
1058 'servedby' => wfHostname(),
1063 [ 'existing-error', 'internal_api_error_DBQueryError' ],
1066 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1069 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1071 'code' => 'internal_api_error_DBQueryError',
1072 'text' => "[$reqId] Exception caught: A database query error has occurred. " .
1073 "This may indicate a bug in the software.",
1075 'errorclass' => DBQueryError
::class,
1079 'trace' => $dbtrace,
1080 'servedby' => wfHostname(),
1085 [ 'existing-error', 'internal_api_error_MediaWiki\ShellDisabledError' ],
1088 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1091 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1093 'code' => 'internal_api_error_MediaWiki\ShellDisabledError',
1094 'text' => "[$reqId] Exception caught: " . $nsex->getMessage(),
1096 'errorclass' => MediaWiki\ShellDisabledError
::class,
1100 'trace' => $nstrace,
1101 'servedby' => wfHostname(),
1106 [ 'existing-error', 'sv-error1', 'sv-error2' ],
1109 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1110 [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
1111 [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
1114 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1115 [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
1116 [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
1118 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1119 "list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> " .
1120 "for notice of API deprecations and breaking changes.",
1121 'servedby' => wfHostname(),
1126 [ 'existing-error', '<invalid-code>' ],
1129 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1132 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1133 [ 'code' => "bad\nvalue", 'text' => 'An error' ],
1135 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1136 "list at <https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce> " .
1137 "for notice of API deprecations and breaking changes.",
1138 'servedby' => wfHostname(),
1144 public function testPrinterParameterValidationError() {
1145 $api = $this->getNonInternalApiMain( [
1146 'action' => 'query', 'meta' => 'siteinfo', 'format' => 'json', 'formatversion' => 'bogus',
1151 $txt = ob_get_clean();
1153 // Test that the actual output is valid JSON, not just the format of the ApiResult.
1154 $data = FormatJson
::decode( $txt, true );
1155 $this->assertInternalType( 'array', $data );
1156 $this->assertArrayHasKey( 'error', $data );
1157 $this->assertArrayHasKey( 'code', $data['error'] );
1158 $this->assertSame( 'unknown_formatversion', $data['error']['code'] );