Localisation updates from https://translatewiki.net.
[mediawiki.git] / tests / phpunit / includes / api / ApiMainTest.php
blobbf38a8e0d586a0d9790501b474a04379cef5c69c
1 <?php
3 namespace MediaWiki\Tests\Api;
5 use Generator;
6 use InvalidArgumentException;
7 use LogicException;
8 use MediaWiki\Api\ApiBase;
9 use MediaWiki\Api\ApiContinuationManager;
10 use MediaWiki\Api\ApiErrorFormatter;
11 use MediaWiki\Api\ApiErrorFormatter_BackCompat;
12 use MediaWiki\Api\ApiMain;
13 use MediaWiki\Api\ApiRawMessage;
14 use MediaWiki\Api\ApiUsageException;
15 use MediaWiki\Config\Config;
16 use MediaWiki\Config\HashConfig;
17 use MediaWiki\Config\MultiConfig;
18 use MediaWiki\Context\RequestContext;
19 use MediaWiki\Json\FormatJson;
20 use MediaWiki\Language\RawMessage;
21 use MediaWiki\MainConfigNames;
22 use MediaWiki\Permissions\Authority;
23 use MediaWiki\Request\FauxRequest;
24 use MediaWiki\Request\FauxResponse;
25 use MediaWiki\Request\WebRequest;
26 use MediaWiki\ShellDisabledError;
27 use MediaWiki\StubObject\StubGlobalUser;
28 use MediaWiki\Tests\Unit\Permissions\MockAuthorityTrait;
29 use MediaWiki\User\User;
30 use MWExceptionHandler;
31 use StatusValue;
32 use UnexpectedValueException;
33 use Wikimedia\Rdbms\DBQueryError;
34 use Wikimedia\Rdbms\IDatabase;
35 use Wikimedia\Rdbms\ILoadBalancer;
36 use Wikimedia\TestingAccessWrapper;
37 use Wikimedia\Timestamp\ConvertibleTimestamp;
39 /**
40 * @group API
41 * @group Database
42 * @group medium
44 * @covers \MediaWiki\Api\ApiMain
46 class ApiMainTest extends ApiTestCase {
47 use MockAuthorityTrait;
49 protected function setUp(): void {
50 parent::setUp();
51 $this->setGroupPermissions( [
52 '*' => [
53 'read' => true,
54 'edit' => true,
55 'apihighlimits' => false,
57 ] );
60 /**
61 * Test that the API will accept a MediaWiki\Request\FauxRequest and execute.
63 public function testApi() {
64 $fauxRequest = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
65 $fauxRequest->setRequestURL( 'https://' );
66 $api = new ApiMain(
67 $fauxRequest
69 $api->execute();
70 $data = $api->getResult()->getResultData();
71 $this->assertIsArray( $data );
72 $this->assertArrayHasKey( 'query', $data );
75 public function testApiNoParam() {
76 $api = new ApiMain();
77 $api->execute();
78 $data = $api->getResult()->getResultData();
79 $this->assertIsArray( $data );
82 /**
83 * ApiMain behaves differently if passed a MediaWiki\Request\FauxRequest (mInternalMode set
84 * to true) or a proper WebRequest (mInternalMode false). For most tests
85 * we can just set mInternalMode to false using TestingAccessWrapper, but
86 * this doesn't work for the constructor. This method returns an ApiMain
87 * that's been set up in non-internal mode.
89 * Note that calling execute() will print to the console. Wrap it in
90 * ob_start()/ob_end_clean() to prevent this.
92 * @param array $requestData Query parameters for the WebRequest
93 * @param array $headers Headers for the WebRequest
94 * @return ApiMain
96 private function getNonInternalApiMain( array $requestData, array $headers = [] ) {
97 $req = $this->getMockBuilder( WebRequest::class )
98 ->onlyMethods( [ 'response', 'getRawIP' ] )
99 ->getMock();
100 $response = new FauxResponse();
101 $req->method( 'response' )->willReturn( $response );
102 $req->method( 'getRawIP' )->willReturn( '127.0.0.1' );
104 $wrapper = TestingAccessWrapper::newFromObject( $req );
105 $wrapper->data = $requestData;
106 if ( $headers ) {
107 $wrapper->headers = $headers;
110 return new ApiMain( $req );
113 public function testUselang() {
114 global $wgLang;
116 $api = $this->getNonInternalApiMain( [
117 'action' => 'query',
118 'meta' => 'siteinfo',
119 'uselang' => 'fr',
120 ] );
122 ob_start();
123 $api->execute();
124 ob_end_clean();
126 $this->assertSame( 'fr', $wgLang->getCode() );
129 public function testSuppressedLogin() {
130 // Testing some logic that changes the global $wgUser
131 // ApiMain will be setting it to a MediaWiki\StubObject\StubGlobalUser object, it should already
132 // be one but in case its a full User object we will wrap the comparisons
133 // in MediaWiki\StubObject\StubGlobalUser::getRealUser() which will return the inner User object
134 // for a MediaWiki\StubObject\StubGlobalUser, or the actual User object if given a user.
136 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgUser
137 global $wgUser;
138 $origUser = StubGlobalUser::getRealUser( $wgUser );
140 $api = $this->getNonInternalApiMain( [
141 'action' => 'query',
142 'meta' => 'siteinfo',
143 'origin' => '*',
144 ] );
146 ob_start();
147 $api->execute();
148 ob_end_clean();
150 $this->assertNotSame( $origUser, StubGlobalUser::getRealUser( $wgUser ) );
151 $this->assertSame( 'true', $api->getContext()->getRequest()->response()
152 ->getHeader( 'MediaWiki-Login-Suppressed' ) );
155 public function testSetContinuationManager() {
156 $api = new ApiMain();
157 $manager = $this->createMock( ApiContinuationManager::class );
158 $api->setContinuationManager( $manager );
159 $this->assertTrue( true, 'No exception' );
162 public function testSetContinuationManagerTwice() {
163 $this->expectException( UnexpectedValueException::class );
164 $this->expectExceptionMessage(
165 'ApiMain::setContinuationManager: tried to set manager from ' .
166 'when a manager is already set from '
169 $api = new ApiMain();
170 $manager = $this->createMock( ApiContinuationManager::class );
171 $api->setContinuationManager( $manager );
172 $api->setContinuationManager( $manager );
175 public function testSetCacheModeUnrecognized() {
176 $api = new ApiMain();
177 $api->setCacheMode( 'unrecognized' );
178 $this->assertSame(
179 'private',
180 TestingAccessWrapper::newFromObject( $api )->mCacheMode,
181 'Unrecognized params must be silently ignored'
185 public function testSetCacheModePrivateWiki() {
186 $this->setGroupPermissions( '*', 'read', false );
187 $wrappedApi = TestingAccessWrapper::newFromObject( new ApiMain() );
188 $wrappedApi->setCacheMode( 'public' );
189 $this->assertSame( 'private', $wrappedApi->mCacheMode );
190 $wrappedApi->setCacheMode( 'anon-public-user-private' );
191 $this->assertSame( 'private', $wrappedApi->mCacheMode );
194 public function testAddRequestedFieldsRequestId() {
195 $req = new FauxRequest( [
196 'action' => 'query',
197 'meta' => 'siteinfo',
198 'requestid' => '123456',
199 ] );
200 $api = new ApiMain( $req );
201 $api->execute();
202 $this->assertSame( '123456', $api->getResult()->getResultData()['requestid'] );
205 public function testAddRequestedFieldsCurTimestamp() {
206 // Fake timestamp for better testability, CI can sometimes take
207 // unreasonably long to run the simple test request here.
208 ConvertibleTimestamp::setFakeTime( '20190102030405' );
210 $req = new FauxRequest( [
211 'action' => 'query',
212 'meta' => 'siteinfo',
213 'curtimestamp' => '',
214 ] );
215 $api = new ApiMain( $req );
216 $api->execute();
217 $timestamp = $api->getResult()->getResultData()['curtimestamp'];
218 $this->assertSame( '2019-01-02T03:04:05Z', $timestamp );
221 public function testAddRequestedFieldsResponseLangInfo() {
222 $req = new FauxRequest( [
223 'action' => 'query',
224 'meta' => 'siteinfo',
225 // errorlang is ignored if errorformat is not specified
226 'errorformat' => 'plaintext',
227 'uselang' => 'FR',
228 'errorlang' => 'ja',
229 'responselanginfo' => '',
230 ] );
231 $api = new ApiMain( $req );
232 $api->execute();
233 $data = $api->getResult()->getResultData();
234 $this->assertSame( 'fr', $data['uselang'] );
235 $this->assertSame( 'ja', $data['errorlang'] );
238 public function testSetupModuleUnknown() {
239 $this->expectApiErrorCode( 'badvalue' );
241 $req = new FauxRequest( [ 'action' => 'unknownaction' ] );
242 $api = new ApiMain( $req );
243 $api->execute();
246 public function testSetupModuleNoTokenProvided() {
247 $this->expectApiErrorCode( 'missingparam' );
249 $req = new FauxRequest( [
250 'action' => 'edit',
251 'title' => 'New page',
252 'text' => 'Some text',
253 ] );
254 $api = new ApiMain( $req );
255 $api->execute();
258 public function testSetupModuleInvalidTokenProvided() {
259 $this->expectApiErrorCode( 'badtoken' );
261 $req = new FauxRequest( [
262 'action' => 'edit',
263 'title' => 'New page',
264 'text' => 'Some text',
265 'token' => "This isn't a real token!",
266 ] );
267 $api = new ApiMain( $req );
268 $api->execute();
271 public function testSetupModuleNeedsTokenTrue() {
272 $this->expectException( LogicException::class );
273 $this->expectExceptionMessage(
274 "Module 'testmodule' must be updated for the new token handling. " .
275 "See documentation for ApiBase::needsToken for details."
278 $mock = $this->createMock( ApiBase::class );
279 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
280 $mock->method( 'needsToken' )->willReturn( true );
282 $api = new ApiMain( new FauxRequest( [ 'action' => 'testmodule' ] ) );
283 $api->getModuleManager()->addModule( 'testmodule', 'action', [
284 'class' => get_class( $mock ),
285 'factory' => static function () use ( $mock ) {
286 return $mock;
288 ] );
289 $api->execute();
292 public function testSetupModuleNeedsTokenNeedntBePosted() {
293 $this->expectException( LogicException::class );
294 $this->expectExceptionMessage( "Module 'testmodule' must require POST to use tokens." );
296 $mock = $this->createMock( ApiBase::class );
297 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
298 $mock->method( 'needsToken' )->willReturn( 'csrf' );
299 $mock->method( 'mustBePosted' )->willReturn( false );
301 $api = new ApiMain( new FauxRequest( [ 'action' => 'testmodule' ] ) );
302 $api->getModuleManager()->addModule( 'testmodule', 'action', [
303 'class' => get_class( $mock ),
304 'factory' => static function () use ( $mock ) {
305 return $mock;
307 ] );
308 $api->execute();
311 public function testCheckMaxLagFailed() {
312 // It's hard to mock the LoadBalancer properly, so instead we'll mock
313 // checkMaxLag (which is tested directly in other tests below).
314 $req = new FauxRequest( [
315 'action' => 'query',
316 'meta' => 'siteinfo',
317 ] );
319 $mock = $this->getMockBuilder( ApiMain::class )
320 ->setConstructorArgs( [ $req ] )
321 ->onlyMethods( [ 'checkMaxLag' ] )
322 ->getMock();
323 $mock->method( 'checkMaxLag' )->willReturn( false );
325 $mock->execute();
327 $this->assertArrayNotHasKey( 'query', $mock->getResult()->getResultData() );
330 public function testCheckConditionalRequestHeadersFailed() {
331 // The detailed checking of all cases of checkConditionalRequestHeaders
332 // is below in testCheckConditionalRequestHeaders(), which calls the
333 // method directly. Here we just check that it will stop execution if
334 // it does fail.
335 $now = time();
337 $this->overrideConfigValue( MainConfigNames::CacheEpoch, '20030516000000' );
339 $mock = $this->createMock( ApiBase::class );
340 $mock->method( 'getModuleName' )->willReturn( 'testmodule' );
341 $mock->method( 'getConditionalRequestData' )
342 ->willReturn( wfTimestamp( TS_MW, $now - 3600 ) );
343 $mock->expects( $this->never() )->method( 'execute' );
345 $req = new FauxRequest( [
346 'action' => 'testmodule',
347 ] );
348 $req->setHeader( 'If-Modified-Since', wfTimestamp( TS_RFC2822, $now - 3600 ) );
349 $req->setRequestURL( "http://localhost" );
351 $api = new ApiMain( $req );
352 $api->getModuleManager()->addModule( 'testmodule', 'action', [
353 'class' => get_class( $mock ),
354 'factory' => static function () use ( $mock ) {
355 return $mock;
357 ] );
359 $wrapper = TestingAccessWrapper::newFromObject( $api );
360 $wrapper->mInternalMode = false;
362 ob_start();
363 $api->execute();
364 ob_end_clean();
367 private function doTestCheckMaxLag( $lag ) {
368 $mockLB = $this->createMock( ILoadBalancer::class );
369 $mockLB->method( 'getMaxLag' )->willReturn( [ 'somehost', $lag ] );
370 $mockLB->method( 'getConnection' )->willReturn( $this->createMock( IDatabase::class ) );
371 $this->setService( 'DBLoadBalancer', $mockLB );
373 $req = new FauxRequest();
375 $api = new ApiMain( $req );
376 $wrapper = TestingAccessWrapper::newFromObject( $api );
378 $mockModule = $this->createMock( ApiBase::class );
379 $mockModule->method( 'shouldCheckMaxLag' )->willReturn( true );
381 try {
382 $wrapper->checkMaxLag( $mockModule, [ 'maxlag' => 3 ] );
383 } finally {
384 if ( $lag > 3 ) {
385 $this->assertSame( '5', $req->response()->getHeader( 'Retry-After' ) );
386 $this->assertSame( (string)$lag, $req->response()->getHeader( 'X-Database-Lag' ) );
391 public function testCheckMaxLagOkay() {
392 $this->doTestCheckMaxLag( 3 );
394 // No exception, we're happy
395 $this->assertTrue( true );
398 public function testCheckMaxLagExceeded() {
399 $this->expectApiErrorCode( 'maxlag' );
401 $this->overrideConfigValue( MainConfigNames::ShowHostnames, false );
403 $this->doTestCheckMaxLag( 4 );
406 public function testCheckMaxLagExceededWithHostNames() {
407 $this->expectApiErrorCode( 'maxlag' );
409 $this->overrideConfigValue( MainConfigNames::ShowHostnames, true );
411 $this->doTestCheckMaxLag( 4 );
414 public function provideAssert() {
415 return [
416 [ $this->mockAnonNullAuthority(), 'user', 'assertuserfailed' ],
417 [ $this->mockRegisteredNullAuthority(), 'user', false ],
418 [ $this->mockAnonNullAuthority(), 'anon', false ],
419 [ $this->mockRegisteredNullAuthority(), 'anon', 'assertanonfailed' ],
420 [ $this->mockRegisteredNullAuthority(), 'bot', 'assertbotfailed' ],
421 [ $this->mockRegisteredAuthorityWithPermissions( [ 'bot' ] ), 'user', false ],
422 [ $this->mockRegisteredAuthorityWithPermissions( [ 'bot' ] ), 'bot', false ],
427 * Tests the assert={user|bot} functionality
429 * @dataProvider provideAssert
431 public function testAssert( Authority $performer, $assert, $error ) {
432 try {
433 $this->doApiRequest( [
434 'action' => 'query',
435 'assert' => $assert,
436 ], null, null, $performer );
437 $this->assertFalse( $error ); // That no error was expected
438 } catch ( ApiUsageException $e ) {
439 $this->assertApiErrorCode( $error, $e,
440 "Error '{$e->getMessage()}' matched expected '$error'" );
445 * Tests the assertuser= functionality
447 public function testAssertUser() {
448 $user = $this->getTestUser()->getUser();
449 $this->doApiRequest( [
450 'action' => 'query',
451 'assertuser' => $user->getName(),
452 ], null, null, $user );
454 try {
455 $this->doApiRequest( [
456 'action' => 'query',
457 'assertuser' => $user->getName() . 'X',
458 ], null, null, $user );
459 $this->fail( 'Expected exception not thrown' );
460 } catch ( ApiUsageException $e ) {
461 $this->assertApiErrorCode( 'assertnameduserfailed', $e );
466 * Test that 'assert' is processed before module errors
468 public function testAssertBeforeModule() {
469 // Check that the query without assert throws too-many-titles
470 try {
471 $this->doApiRequest( [
472 'action' => 'query',
473 'titles' => implode( '|', range( 1, ApiBase::LIMIT_SML1 + 1 ) ),
474 ], null, null, new User );
475 $this->fail( 'Expected exception not thrown' );
476 } catch ( ApiUsageException $e ) {
477 $this->assertApiErrorCode( 'toomanyvalues', $e );
480 // Now test that the assert happens first
481 try {
482 $this->doApiRequest( [
483 'action' => 'query',
484 'titles' => implode( '|', range( 1, ApiBase::LIMIT_SML1 + 1 ) ),
485 'assert' => 'user',
486 ], null, null, new User );
487 $this->fail( 'Expected exception not thrown' );
488 } catch ( ApiUsageException $e ) {
489 $this->assertApiErrorCode( 'assertuserfailed', $e,
490 "Error '{$e->getMessage()}' matched expected 'assertuserfailed'" );
495 * Test if all classes in the main module manager exists
497 public function testClassNamesInModuleManager() {
498 $api = new ApiMain(
499 new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
501 $modules = $api->getModuleManager()->getNamesWithClasses();
503 foreach ( $modules as $name => $class ) {
504 $this->assertTrue(
505 class_exists( $class ),
506 'Class ' . $class . ' for api module ' . $name . ' does not exist (with exact case)'
512 * Test HTTP precondition headers
514 * @dataProvider provideCheckConditionalRequestHeaders
515 * @param array $headers HTTP headers
516 * @param array $conditions Return data for ApiBase::getConditionalRequestData
517 * @param int $status Expected response status
518 * @param array $options Array of options:
519 * post => true Request is a POST
520 * cdn => true CDN is enabled ($wgUseCdn)
522 public function testCheckConditionalRequestHeaders(
523 $headers, $conditions, $status, $options = []
525 $request = new FauxRequest(
526 [ 'action' => 'query', 'meta' => 'siteinfo' ],
527 !empty( $options['post'] )
529 $request->setHeaders( $headers );
530 $request->response()->statusHeader( 200 ); // Why doesn't it default?
532 $context = $this->apiContext->newTestContext( $request, null );
533 $api = new ApiMain( $context );
534 $priv = TestingAccessWrapper::newFromObject( $api );
535 $priv->mInternalMode = false;
537 if ( !empty( $options['cdn'] ) ) {
538 $this->overrideConfigValue( MainConfigNames::UseCdn, true );
541 // Can't do this in TestSetup.php because Setup.php will override it
542 $this->overrideConfigValue( MainConfigNames::CacheEpoch, '20030516000000' );
544 $module = $this->getMockBuilder( ApiBase::class )
545 ->setConstructorArgs( [ $api, 'mock' ] )
546 ->onlyMethods( [ 'getConditionalRequestData' ] )
547 ->getMockForAbstractClass();
548 $module->method( 'getConditionalRequestData' )
549 ->willReturnCallback( static function ( $condition ) use ( $conditions ) {
550 return $conditions[$condition] ?? null;
551 } );
553 $ret = $priv->checkConditionalRequestHeaders( $module );
555 $this->assertSame( $status, $request->response()->getStatusCode() );
556 $this->assertSame( $status === 200, $ret );
559 public static function provideCheckConditionalRequestHeaders() {
560 global $wgCdnMaxAge;
561 $now = time();
563 return [
564 // Non-existing from module is ignored
565 'If-None-Match' => [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
566 'If-Modified-Since' =>
567 [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
569 // No headers
570 'No headers' => [ [], [ 'etag' => '""', 'last-modified' => '20150815000000', ], 200 ],
572 // Basic If-None-Match
573 'If-None-Match with matching etag' =>
574 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
575 'If-None-Match with non-matching etag' =>
576 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
577 'Strong If-None-Match with weak matching etag' =>
578 [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
579 'Weak If-None-Match with strong matching etag' =>
580 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
581 'Weak If-None-Match with weak matching etag' =>
582 [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
584 // Pointless for GET, but supported
585 'If-None-Match: *' => [ [ 'If-None-Match' => '*' ], [], 304 ],
587 // Basic If-Modified-Since
588 'If-Modified-Since, modified one second earlier' =>
589 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
590 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
591 'If-Modified-Since, modified now' =>
592 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
593 [ 'last-modified' => wfTimestamp( TS_MW, $now ) ], 304 ],
594 'If-Modified-Since, modified one second later' =>
595 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
596 [ 'last-modified' => wfTimestamp( TS_MW, $now + 1 ) ], 200 ],
598 // If-Modified-Since ignored when If-None-Match is given too
599 'Non-matching If-None-Match and matching If-Modified-Since' =>
600 [ [ 'If-None-Match' => '""',
601 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
602 [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
603 'Non-matching If-None-Match and matching If-Modified-Since with no ETag' =>
606 'If-None-Match' => '""',
607 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now )
609 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ],
613 // Ignored for POST
614 'Matching If-None-Match with POST' =>
615 [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200,
616 [ 'post' => true ] ],
617 'Matching If-Modified-Since with POST' =>
618 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
619 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200,
620 [ 'post' => true ] ],
622 // Other date formats allowed by the RFC
623 'If-Modified-Since with alternate date format 1' =>
624 [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
625 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
626 'If-Modified-Since with alternate date format 2' =>
627 [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
628 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
630 // Old browser extension to HTTP/1.0
631 'If-Modified-Since with length' =>
632 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) . '; length=123' ],
633 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
635 // Invalid date formats should be ignored
636 'If-Modified-Since with invalid date format' =>
637 [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
638 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
639 'If-Modified-Since with entirely unparseable date' =>
640 [ [ 'If-Modified-Since' => 'a potato' ],
641 [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
643 // Anything before $wgCdnMaxAge seconds ago should be considered
644 // expired.
645 'If-Modified-Since with CDN post-expiry' =>
646 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now - $wgCdnMaxAge * 2 ) ],
647 [ 'last-modified' => wfTimestamp( TS_MW, $now - $wgCdnMaxAge * 3 ) ],
648 200, [ 'cdn' => true ] ],
649 'If-Modified-Since with CDN pre-expiry' =>
650 [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now - $wgCdnMaxAge / 2 ) ],
651 [ 'last-modified' => wfTimestamp( TS_MW, $now - $wgCdnMaxAge * 3 ) ],
652 304, [ 'cdn' => true ] ],
657 * Test conditional headers output
658 * @dataProvider provideConditionalRequestHeadersOutput
659 * @param array $conditions Return data for ApiBase::getConditionalRequestData
660 * @param array $headers Expected output headers
661 * @param bool $isError $isError flag
662 * @param bool $post Request is a POST
664 public function testConditionalRequestHeadersOutput(
665 $conditions, $headers, $isError = false, $post = false
667 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
668 $response = $request->response();
670 $api = new ApiMain( $request );
671 $priv = TestingAccessWrapper::newFromObject( $api );
672 $priv->mInternalMode = false;
674 $module = $this->getMockBuilder( ApiBase::class )
675 ->setConstructorArgs( [ $api, 'mock' ] )
676 ->onlyMethods( [ 'getConditionalRequestData' ] )
677 ->getMockForAbstractClass();
678 $module->method( 'getConditionalRequestData' )
679 ->willReturnCallback( static function ( $condition ) use ( $conditions ) {
680 return $conditions[$condition] ?? null;
681 } );
682 $priv->mModule = $module;
684 $priv->sendCacheHeaders( $isError );
686 foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
687 $this->assertEquals(
688 $headers[$header] ?? null,
689 $response->getHeader( $header ),
690 $header
695 public static function provideConditionalRequestHeadersOutput() {
696 return [
702 [ 'etag' => '"foo"' ],
703 [ 'ETag' => '"foo"' ]
706 [ 'last-modified' => '20150818000102' ],
707 [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
710 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
711 [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
714 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
716 true,
719 [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
721 false,
722 true,
727 public function testCheckExecutePermissionsReadProhibited() {
728 $this->expectApiErrorCode( 'readapidenied' );
730 $this->setGroupPermissions( '*', 'read', false );
732 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
733 $main->execute();
736 public function testCheckExecutePermissionWriteDisabled() {
737 $this->expectApiErrorCode( 'noapiwrite' );
738 $main = new ApiMain( new FauxRequest( [
739 'action' => 'edit',
740 'title' => 'Some page',
741 'text' => 'Some text',
742 'token' => '+\\',
743 ] ) );
744 $main->execute();
747 public function testCheckExecutePermissionPromiseNonWrite() {
748 $this->expectApiErrorCode( 'promised-nonwrite-api' );
750 $req = new FauxRequest( [
751 'action' => 'edit',
752 'title' => 'Some page',
753 'text' => 'Some text',
754 'token' => '+\\',
755 ] );
756 $req->setHeaders( [ 'Promise-Non-Write-API-Action' => '1' ] );
757 $main = new ApiMain( $req, /* enableWrite = */ true );
758 $main->execute();
761 public function testCheckExecutePermissionHookAbort() {
762 $this->expectApiErrorCode( 'mainpage' );
764 $this->setTemporaryHook( 'ApiCheckCanExecute', static function ( $unused1, $unused2, &$message ) {
765 $message = 'mainpage';
766 return false;
767 } );
769 $main = new ApiMain( new FauxRequest( [
770 'action' => 'edit',
771 'title' => 'Some page',
772 'text' => 'Some text',
773 'token' => '+\\',
774 ] ), /* enableWrite = */ true );
775 $main->execute();
778 public function testGetValUnsupportedArray() {
779 $main = new ApiMain( new FauxRequest( [
780 'action' => 'query',
781 'meta' => 'siteinfo',
782 'siprop' => [ 'general', 'namespaces' ],
783 ] ) );
784 $this->assertSame( 'myDefault', $main->getVal( 'siprop', 'myDefault' ) );
785 $main->execute();
786 $this->assertSame( 'Parameter "siprop" uses unsupported PHP array syntax.',
787 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
790 public function testReportUnusedParams() {
791 $main = new ApiMain( new FauxRequest( [
792 'action' => 'query',
793 'meta' => 'siteinfo',
794 'unusedparam' => 'unusedval',
795 'anotherunusedparam' => 'anotherval',
796 ] ) );
797 $main->execute();
798 $this->assertSame( 'Unrecognized parameters: unusedparam, anotherunusedparam.',
799 $main->getResult()->getResultData()['warnings']['main']['warnings'] );
802 public function testLacksSameOriginSecurity() {
803 // Basic test
804 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
805 $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
807 // JSONp
808 $main = new ApiMain(
809 new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
811 $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
813 // Header
814 $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
815 $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
816 $main = new ApiMain( $request );
817 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
819 // Hook
820 $this->mergeMwGlobalArrayValue( 'wgHooks', [
821 'RequestHasSameOriginSecurity' => [ static function () {
822 return false;
824 ] );
825 $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
826 $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
830 * Test proper creation of the ApiErrorFormatter
832 * @dataProvider provideApiErrorFormatterCreation
833 * @param array $request Request parameters
834 * @param array $expect Expected data
835 * - uselang: ApiMain language
836 * - class: ApiErrorFormatter class
837 * - lang: ApiErrorFormatter language
838 * - format: ApiErrorFormatter format
839 * - usedb: ApiErrorFormatter use-database flag
841 public function testApiErrorFormatterCreation( array $request, array $expect ) {
842 $context = new RequestContext();
843 $context->setRequest( new FauxRequest( $request ) );
844 $context->setLanguage( 'ru' );
846 $main = new ApiMain( $context );
847 $formatter = $main->getErrorFormatter();
848 $wrappedFormatter = TestingAccessWrapper::newFromObject( $formatter );
850 $this->assertSame( $expect['uselang'], $main->getLanguage()->getCode() );
851 $this->assertInstanceOf( $expect['class'], $formatter );
852 $this->assertSame( $expect['lang'], $formatter->getLanguage()->getCode() );
853 $this->assertSame( $expect['format'], $wrappedFormatter->format );
854 $this->assertSame( $expect['usedb'], $wrappedFormatter->useDB );
857 public static function provideApiErrorFormatterCreation() {
858 return [
859 'Default (BC)' => [ [], [
860 'uselang' => 'ru',
861 'class' => ApiErrorFormatter_BackCompat::class,
862 'lang' => 'en',
863 'format' => 'none',
864 'usedb' => false,
865 ] ],
866 'BC ignores fields' => [ [ 'errorlang' => 'de', 'errorsuselocal' => 1 ], [
867 'uselang' => 'ru',
868 'class' => ApiErrorFormatter_BackCompat::class,
869 'lang' => 'en',
870 'format' => 'none',
871 'usedb' => false,
872 ] ],
873 'Explicit BC' => [ [ 'errorformat' => 'bc' ], [
874 'uselang' => 'ru',
875 'class' => ApiErrorFormatter_BackCompat::class,
876 'lang' => 'en',
877 'format' => 'none',
878 'usedb' => false,
879 ] ],
880 'Basic' => [ [ 'errorformat' => 'wikitext' ], [
881 'uselang' => 'ru',
882 'class' => ApiErrorFormatter::class,
883 'lang' => 'ru',
884 'format' => 'wikitext',
885 'usedb' => false,
886 ] ],
887 'Follows uselang' => [ [ 'uselang' => 'fr', 'errorformat' => 'plaintext' ], [
888 'uselang' => 'fr',
889 'class' => ApiErrorFormatter::class,
890 'lang' => 'fr',
891 'format' => 'plaintext',
892 'usedb' => false,
893 ] ],
894 'Explicitly follows uselang' => [
895 [ 'uselang' => 'fr', 'errorlang' => 'uselang', 'errorformat' => 'plaintext' ],
897 'uselang' => 'fr',
898 'class' => ApiErrorFormatter::class,
899 'lang' => 'fr',
900 'format' => 'plaintext',
901 'usedb' => false,
904 'uselang=content' => [
905 [ 'uselang' => 'content', 'errorformat' => 'plaintext' ],
907 'uselang' => 'en',
908 'class' => ApiErrorFormatter::class,
909 'lang' => 'en',
910 'format' => 'plaintext',
911 'usedb' => false,
914 'errorlang=content' => [
915 [ 'errorlang' => 'content', 'errorformat' => 'plaintext' ],
917 'uselang' => 'ru',
918 'class' => ApiErrorFormatter::class,
919 'lang' => 'en',
920 'format' => 'plaintext',
921 'usedb' => false,
924 'Explicit parameters' => [
925 [ 'errorlang' => 'de', 'errorformat' => 'html', 'errorsuselocal' => 1 ],
927 'uselang' => 'ru',
928 'class' => ApiErrorFormatter::class,
929 'lang' => 'de',
930 'format' => 'html',
931 'usedb' => true,
934 'Explicit parameters override uselang' => [
935 [ 'errorlang' => 'de', 'uselang' => 'fr', 'errorformat' => 'raw' ],
937 'uselang' => 'fr',
938 'class' => ApiErrorFormatter::class,
939 'lang' => 'de',
940 'format' => 'raw',
941 'usedb' => false,
944 'Bogus language doesn\'t explode' => [
945 [ 'errorlang' => '<bogus1>', 'uselang' => '<bogus2>', 'errorformat' => 'none' ],
947 'uselang' => 'en',
948 'class' => ApiErrorFormatter::class,
949 'lang' => 'en',
950 'format' => 'none',
951 'usedb' => false,
954 'Bogus format doesn\'t explode' => [ [ 'errorformat' => 'bogus' ], [
955 'uselang' => 'ru',
956 'class' => ApiErrorFormatter_BackCompat::class,
957 'lang' => 'en',
958 'format' => 'none',
959 'usedb' => false,
960 ] ],
965 * @dataProvider provideExceptionErrors
967 public function testExceptionErrors( $error, $expectReturn, $expectResult ) {
968 $this->overrideConfigValues( [
969 MainConfigNames::Server => 'https://local.example',
970 MainConfigNames::ScriptPath => '/w',
971 ] );
972 $context = new RequestContext();
973 $context->setRequest( new FauxRequest( [ 'errorformat' => 'plaintext' ] ) );
974 $context->setLanguage( 'en' );
975 $context->setConfig( new MultiConfig( [
976 new HashConfig( [
977 MainConfigNames::ShowHostnames => true, MainConfigNames::ShowExceptionDetails => true,
978 ] ),
979 $context->getConfig()
980 ] ) );
982 $main = new ApiMain( $context );
983 $main->addWarning( new RawMessage( 'existing warning' ), 'existing-warning' );
984 $main->addError( new RawMessage( 'existing error' ), 'existing-error' );
986 $ret = TestingAccessWrapper::newFromObject( $main )->substituteResultWithError( $error );
987 $this->assertSame( $expectReturn, $ret );
989 // PHPUnit sometimes adds some SplObjectStorage garbage to the arrays,
990 // so let's try ->assertEquals().
991 $this->assertEquals(
992 $expectResult,
993 $main->getResult()->getResultData( [], [ 'Strip' => 'all' ] )
997 // Not static so $this can be used
998 public function provideExceptionErrors() {
999 $reqId = WebRequest::getRequestId();
1000 $doclink = 'https://local.example/w/api.php';
1002 $ex = new InvalidArgumentException( 'Random exception' );
1003 $trace = wfMessage( 'api-exception-trace',
1004 get_class( $ex ),
1005 $ex->getFile(),
1006 $ex->getLine(),
1007 MWExceptionHandler::getRedactedTraceAsString( $ex )
1008 )->inLanguage( 'en' )->useDatabase( false )->text();
1010 $dbex = new DBQueryError(
1011 $this->createMock( IDatabase::class ),
1012 'error', 1234, 'SELECT 1', __METHOD__ );
1013 $dbtrace = wfMessage( 'api-exception-trace',
1014 get_class( $dbex ),
1015 $dbex->getFile(),
1016 $dbex->getLine(),
1017 MWExceptionHandler::getRedactedTraceAsString( $dbex )
1018 )->inLanguage( 'en' )->useDatabase( false )->text();
1020 // The specific exception doesn't matter, as long as it's namespaced.
1021 $nsex = new ShellDisabledError();
1022 $nstrace = wfMessage( 'api-exception-trace',
1023 get_class( $nsex ),
1024 $nsex->getFile(),
1025 $nsex->getLine(),
1026 MWExceptionHandler::getRedactedTraceAsString( $nsex )
1027 )->inLanguage( 'en' )->useDatabase( false )->text();
1029 $apiEx1 = new ApiUsageException( null,
1030 StatusValue::newFatal( new ApiRawMessage( 'An error', 'sv-error1' ) ) );
1031 TestingAccessWrapper::newFromObject( $apiEx1 )->modulePath = 'foo+bar';
1032 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'A warning', 'sv-warn1' ) );
1033 $apiEx1->getStatusValue()->warning( new ApiRawMessage( 'Another warning', 'sv-warn2' ) );
1034 $apiEx1->getStatusValue()->fatal( new ApiRawMessage( 'Another error', 'sv-error2' ) );
1036 $badMsg = $this->getMockBuilder( ApiRawMessage::class )
1037 ->setConstructorArgs( [ 'An error', 'ignored' ] )
1038 ->onlyMethods( [ 'getApiCode' ] )
1039 ->getMock();
1040 $badMsg->method( 'getApiCode' )->willReturn( "bad\nvalue" );
1041 $apiEx2 = new ApiUsageException( null, StatusValue::newFatal( $badMsg ) );
1043 return [
1045 $ex,
1046 [ 'existing-error', 'internal_api_error_InvalidArgumentException' ],
1048 'warnings' => [
1049 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1051 'errors' => [
1052 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1054 'code' => 'internal_api_error_InvalidArgumentException',
1055 'text' => "[$reqId] Exception caught: Random exception",
1056 'data' => [
1057 'errorclass' => InvalidArgumentException::class,
1061 'trace' => $trace,
1062 'servedby' => wfHostname(),
1066 $dbex,
1067 [ 'existing-error', 'internal_api_error_DBQueryError' ],
1069 'warnings' => [
1070 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1072 'errors' => [
1073 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1075 'code' => 'internal_api_error_DBQueryError',
1076 'text' => "[$reqId] Exception caught: A database query error has occurred. " .
1077 "This may indicate a bug in the software.",
1078 'data' => [
1079 'errorclass' => DBQueryError::class,
1083 'trace' => $dbtrace,
1084 'servedby' => wfHostname(),
1088 $nsex,
1089 [ 'existing-error', 'internal_api_error_MediaWiki\ShellDisabledError' ],
1091 'warnings' => [
1092 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1094 'errors' => [
1095 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1097 'code' => 'internal_api_error_MediaWiki\ShellDisabledError',
1098 'text' => "[$reqId] Exception caught: " . $nsex->getMessage(),
1099 'data' => [
1100 'errorclass' => ShellDisabledError::class,
1104 'trace' => $nstrace,
1105 'servedby' => wfHostname(),
1109 $apiEx1,
1110 [ 'existing-error', 'sv-error1', 'sv-error2' ],
1112 'warnings' => [
1113 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1114 [ 'code' => 'sv-warn1', 'text' => 'A warning', 'module' => 'foo+bar' ],
1115 [ 'code' => 'sv-warn2', 'text' => 'Another warning', 'module' => 'foo+bar' ],
1117 'errors' => [
1118 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1119 [ 'code' => 'sv-error1', 'text' => 'An error', 'module' => 'foo+bar' ],
1120 [ 'code' => 'sv-error2', 'text' => 'Another error', 'module' => 'foo+bar' ],
1122 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1123 "list at &lt;https://lists.wikimedia.org/postorius/lists/mediawiki-api-announce.lists.wikimedia.org/&gt; " .
1124 "for notice of API deprecations and breaking changes.",
1125 'servedby' => wfHostname(),
1129 $apiEx2,
1130 [ 'existing-error', '<invalid-code>' ],
1132 'warnings' => [
1133 [ 'code' => 'existing-warning', 'text' => 'existing warning', 'module' => 'main' ],
1135 'errors' => [
1136 [ 'code' => 'existing-error', 'text' => 'existing error', 'module' => 'main' ],
1137 [ 'code' => "bad\nvalue", 'text' => 'An error' ],
1139 'docref' => "See $doclink for API usage. Subscribe to the mediawiki-api-announce mailing " .
1140 "list at &lt;https://lists.wikimedia.org/postorius/lists/mediawiki-api-announce.lists.wikimedia.org/&gt; " .
1141 "for notice of API deprecations and breaking changes.",
1142 'servedby' => wfHostname(),
1148 public function testPrinterParameterValidationError() {
1149 $api = $this->getNonInternalApiMain( [
1150 'action' => 'query', 'meta' => 'siteinfo', 'format' => 'json', 'formatversion' => 'bogus',
1151 ] );
1153 ob_start();
1154 $api->execute();
1155 $txt = ob_get_clean();
1157 // Test that the actual output is valid JSON, not just the format of the ApiResult.
1158 $data = FormatJson::decode( $txt, true );
1159 $this->assertIsArray( $data );
1160 $this->assertArrayHasKey( 'error', $data );
1161 $this->assertArrayHasKey( 'code', $data['error'] );
1162 $this->assertSame( 'badvalue', $data['error']['code'] );
1165 public function testMatchRequestedHeaders() {
1166 $api = TestingAccessWrapper::newFromClass( ApiMain::class );
1167 $allowedHeaders = [ 'Accept', 'Origin', 'User-Agent' ];
1169 $this->assertTrue( $api->matchRequestedHeaders( 'Accept', $allowedHeaders ) );
1170 $this->assertTrue( $api->matchRequestedHeaders( 'Accept,Origin', $allowedHeaders ) );
1171 $this->assertTrue( $api->matchRequestedHeaders( 'accEpt, oRIGIN', $allowedHeaders ) );
1172 $this->assertFalse( $api->matchRequestedHeaders( 'Accept,Foo', $allowedHeaders ) );
1173 $this->assertFalse( $api->matchRequestedHeaders( 'Accept, fOO', $allowedHeaders ) );
1177 * Common test code for tests that cover ApiMain::sendCacheHeaders.
1179 * @param TestingAccessWrapper $api An ApiMain instance, wrapped in a TestingAccessWrapper.
1180 * @param FauxRequest $req
1181 * @param bool $isError
1182 * @param string $cacheMode
1183 * @param string|null $expectedVary
1184 * @param string $expectedCacheControl
1186 private function commonTestCacheHeaders(
1187 TestingAccessWrapper $api,
1188 FauxRequest $req,
1189 bool $isError,
1190 string $cacheMode,
1191 ?string $expectedVary,
1192 string $expectedCacheControl
1194 $api->setCacheMode( $cacheMode );
1195 $this->assertSame( $cacheMode, $api->mCacheMode, 'Cache mode precondition' );
1196 $api->sendCacheHeaders( $isError );
1198 $this->assertSame( $expectedVary, $req->response()->getHeader( 'Vary' ), 'Vary' );
1199 $this->assertSame( $expectedCacheControl, $req->response()->getHeader( 'Cache-Control' ), 'Cache-Control' );
1203 * @param string $cacheMode
1204 * @param string|null $expectedVary
1205 * @param string $expectedCacheControl
1206 * @param array $requestData
1207 * @param Config|null $config
1208 * @dataProvider provideCacheHeaders
1210 public function testCacheHeaders(
1211 string $cacheMode,
1212 ?string $expectedVary,
1213 string $expectedCacheControl,
1214 array $requestData = [],
1215 ?Config $config = null
1217 $req = new FauxRequest( $requestData );
1218 $ctx = new RequestContext();
1219 $ctx->setRequest( $req );
1220 if ( $config ) {
1221 $ctx->setConfig( $config );
1223 /** @var ApiMain|TestingAccessWrapper $api */
1224 $api = TestingAccessWrapper::newFromObject( new ApiMain( $ctx ) );
1226 $this->commonTestCacheHeaders( $api, $req, false, $cacheMode, $expectedVary, $expectedCacheControl );
1229 public static function provideCacheHeaders(): Generator {
1230 yield 'Private' => [ 'private', null, 'private, must-revalidate, max-age=0' ];
1231 yield 'Public' => [
1232 'public',
1233 'Accept-Encoding, Treat-as-Untrusted, Cookie',
1234 'private, must-revalidate, max-age=0',
1235 [ 'uselang' => 'en' ]
1237 yield 'Anon public, user private' => [
1238 'anon-public-user-private',
1239 'Accept-Encoding, Treat-as-Untrusted, Cookie',
1240 'private, must-revalidate, max-age=0'
1244 /** @dataProvider provideCacheHeaders */
1245 public function testCacheHeadersOnIsErrorAsTrue(
1246 string $cacheMode,
1247 ?string $expectedVary,
1248 string $expectedCacheControl,
1249 array $requestData = []
1251 $req = new FauxRequest( $requestData );
1252 $ctx = new RequestContext();
1253 $ctx->setRequest( $req );
1254 /** @var ApiMain|TestingAccessWrapper $api */
1255 $api = TestingAccessWrapper::newFromObject( new ApiMain( $ctx ) );
1257 // Create a mock ApiBase object that throws an ApiUsageException from ::isWriteMode. This will be used as the
1258 // mModule property of $api, and will test that ::isWriteMode is either never called or properly wrapped in
1259 // a try block in the method we are testing (T363133).
1260 $module = $this->getMockBuilder( ApiBase::class )
1261 ->setConstructorArgs( [ $api->object, 'mock' ] )
1262 ->onlyMethods( [ 'isWriteMode' ] )
1263 ->getMockForAbstractClass();
1264 $module->method( 'isWriteMode' )
1265 ->willThrowException( new ApiUsageException( $module, StatusValue::newFatal( 'test' ) ) );
1266 $api->mModule = $module;
1268 // This will test that ::isWriteMode will not be called if $isError is true.
1269 $this->commonTestCacheHeaders( $api, $req, true, $cacheMode, $expectedVary, $expectedCacheControl );