MediaWiki  1.27.2
ApiMainTest.php
Go to the documentation of this file.
1 <?php
2 
9 class ApiMainTest extends ApiTestCase {
10 
14  public function testApi() {
15  $api = new ApiMain(
16  new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
17  );
18  $api->execute();
19  $data = $api->getResult()->getResultData();
20  $this->assertInternalType( 'array', $data );
21  $this->assertArrayHasKey( 'query', $data );
22  }
23 
24  public static function provideAssert() {
25  return [
26  [ false, [], 'user', 'assertuserfailed' ],
27  [ true, [], 'user', false ],
28  [ true, [], 'bot', 'assertbotfailed' ],
29  [ true, [ 'bot' ], 'user', false ],
30  [ true, [ 'bot' ], 'bot', false ],
31  ];
32  }
33 
44  public function testAssert( $registered, $rights, $assert, $error ) {
45  $user = new User();
46  if ( $registered ) {
47  $user->setId( 1 );
48  }
49  $user->mRights = $rights;
50  try {
51  $this->doApiRequest( [
52  'action' => 'query',
53  'assert' => $assert,
54  ], null, null, $user );
55  $this->assertFalse( $error ); // That no error was expected
56  } catch ( UsageException $e ) {
57  $this->assertEquals( $e->getCodeString(), $error );
58  }
59  }
60 
64  public function testClassNamesInModuleManager() {
66 
67  // wgAutoloadLocalClasses has precedence, just like in includes/AutoLoader.php
68  $classes = $wgAutoloadLocalClasses + $wgAutoloadClasses;
69 
70  $api = new ApiMain(
71  new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] )
72  );
73  $modules = $api->getModuleManager()->getNamesWithClasses();
74  foreach ( $modules as $name => $class ) {
75  $this->assertArrayHasKey(
76  $class,
77  $classes,
78  'Class ' . $class . ' for api module ' . $name . ' not in autoloader (with exact case)'
79  );
80  }
81  }
82 
94  $headers, $conditions, $status, $post = false
95  ) {
96  $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
97  $request->setHeaders( $headers );
98  $request->response()->statusHeader( 200 ); // Why doesn't it default?
99 
100  $context = $this->apiContext->newTestContext( $request, null );
101  $api = new ApiMain( $context );
102  $priv = TestingAccessWrapper::newFromObject( $api );
103  $priv->mInternalMode = false;
104 
105  $module = $this->getMockBuilder( 'ApiBase' )
106  ->setConstructorArgs( [ $api, 'mock' ] )
107  ->setMethods( [ 'getConditionalRequestData' ] )
108  ->getMockForAbstractClass();
109  $module->expects( $this->any() )
110  ->method( 'getConditionalRequestData' )
111  ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
112  return isset( $conditions[$condition] ) ? $conditions[$condition] : null;
113  } ) );
114 
115  $ret = $priv->checkConditionalRequestHeaders( $module );
116 
117  $this->assertSame( $status, $request->response()->getStatusCode() );
118  $this->assertSame( $status === 200, $ret );
119  }
120 
121  public static function provideCheckConditionalRequestHeaders() {
122  $now = time();
123 
124  return [
125  // Non-existing from module is ignored
126  [ [ 'If-None-Match' => '"foo", "bar"' ], [], 200 ],
127  [ [ 'If-Modified-Since' => 'Tue, 18 Aug 2015 00:00:00 GMT' ], [], 200 ],
128 
129  // No headers
130  [
131  [],
132  [
133  'etag' => '""',
134  'last-modified' => '20150815000000',
135  ],
136  200
137  ],
138 
139  // Basic If-None-Match
140  [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 304 ],
141  [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"baz"' ], 200 ],
142  [ [ 'If-None-Match' => '"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
143  [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => '"foo"' ], 304 ],
144  [ [ 'If-None-Match' => 'W/"foo"' ], [ 'etag' => 'W/"foo"' ], 304 ],
145 
146  // Pointless, but supported
147  [ [ 'If-None-Match' => '*' ], [], 304 ],
148 
149  // Basic If-Modified-Since
150  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
151  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
152  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
153  [ 'last-modified' => wfTimestamp( TS_MW, $now ) ], 304 ],
154  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
155  [ 'last-modified' => wfTimestamp( TS_MW, $now + 1 ) ], 200 ],
156 
157  // If-Modified-Since ignored when If-None-Match is given too
158  [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
159  [ 'etag' => '"x"', 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
160  [ [ 'If-None-Match' => '""', 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
161  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
162 
163  // Ignored for POST
164  [ [ 'If-None-Match' => '"foo", "bar"' ], [ 'etag' => '"bar"' ], 200, true ],
165  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) ],
166  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200, true ],
167 
168  // Other date formats allowed by the RFC
169  [ [ 'If-Modified-Since' => gmdate( 'l, d-M-y H:i:s', $now ) . ' GMT' ],
170  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
171  [ [ 'If-Modified-Since' => gmdate( 'D M j H:i:s Y', $now ) ],
172  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
173 
174  // Old browser extension to HTTP/1.0
175  [ [ 'If-Modified-Since' => wfTimestamp( TS_RFC2822, $now ) . '; length=123' ],
176  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 304 ],
177 
178  // Invalid date formats should be ignored
179  [ [ 'If-Modified-Since' => gmdate( 'Y-m-d H:i:s', $now ) . ' GMT' ],
180  [ 'last-modified' => wfTimestamp( TS_MW, $now - 1 ) ], 200 ],
181  ];
182  }
183 
193  $conditions, $headers, $isError = false, $post = false
194  ) {
195  $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ], $post );
196  $response = $request->response();
197 
198  $api = new ApiMain( $request );
199  $priv = TestingAccessWrapper::newFromObject( $api );
200  $priv->mInternalMode = false;
201 
202  $module = $this->getMockBuilder( 'ApiBase' )
203  ->setConstructorArgs( [ $api, 'mock' ] )
204  ->setMethods( [ 'getConditionalRequestData' ] )
205  ->getMockForAbstractClass();
206  $module->expects( $this->any() )
207  ->method( 'getConditionalRequestData' )
208  ->will( $this->returnCallback( function ( $condition ) use ( $conditions ) {
209  return isset( $conditions[$condition] ) ? $conditions[$condition] : null;
210  } ) );
211  $priv->mModule = $module;
212 
213  $priv->sendCacheHeaders( $isError );
214 
215  foreach ( [ 'Last-Modified', 'ETag' ] as $header ) {
216  $this->assertEquals(
217  isset( $headers[$header] ) ? $headers[$header] : null,
218  $response->getHeader( $header ),
219  $header
220  );
221  }
222  }
223 
224  public static function provideConditionalRequestHeadersOutput() {
225  return [
226  [
227  [],
228  []
229  ],
230  [
231  [ 'etag' => '"foo"' ],
232  [ 'ETag' => '"foo"' ]
233  ],
234  [
235  [ 'last-modified' => '20150818000102' ],
236  [ 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
237  ],
238  [
239  [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
240  [ 'ETag' => '"foo"', 'Last-Modified' => 'Tue, 18 Aug 2015 00:01:02 GMT' ]
241  ],
242  [
243  [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
244  [],
245  true,
246  ],
247  [
248  [ 'etag' => '"foo"', 'last-modified' => '20150818000102' ],
249  [],
250  false,
251  true,
252  ],
253  ];
254  }
255 
259  public function testLacksSameOriginSecurity() {
260  // Basic test
261  $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
262  $this->assertFalse( $main->lacksSameOriginSecurity(), 'Basic test, should have security' );
263 
264  // JSONp
265  $main = new ApiMain(
266  new FauxRequest( [ 'action' => 'query', 'format' => 'xml', 'callback' => 'foo' ] )
267  );
268  $this->assertTrue( $main->lacksSameOriginSecurity(), 'JSONp, should lack security' );
269 
270  // Header
271  $request = new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] );
272  $request->setHeader( 'TrEaT-As-UnTrUsTeD', '' ); // With falsey value!
273  $main = new ApiMain( $request );
274  $this->assertTrue( $main->lacksSameOriginSecurity(), 'Header supplied, should lack security' );
275 
276  // Hook
277  $this->mergeMwGlobalArrayValue( 'wgHooks', [
278  'RequestHasSameOriginSecurity' => [ function () {
279  return false;
280  } ]
281  ] );
282  $main = new ApiMain( new FauxRequest( [ 'action' => 'query', 'meta' => 'siteinfo' ] ) );
283  $this->assertTrue( $main->lacksSameOriginSecurity(), 'Hook, should lack security' );
284  }
285 }
const TS_RFC2822
RFC 2822 format, for E-mail and HTTP headers.
mergeMwGlobalArrayValue($name, $values)
Merges the given values into a MW global array variable.
$context
Definition: load.php:44
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1932
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1798
testApi()
Test that the API will accept a FauxRequest and execute.
Definition: ApiMainTest.php:14
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
this hook is for auditing only $response
Definition: hooks.txt:762
API medium.
Definition: ApiMainTest.php:9
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
testCheckConditionalRequestHeaders($headers, $conditions, $status, $post=false)
Test HTTP precondition headers.
Definition: ApiMainTest.php:93
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1798
static provideCheckConditionalRequestHeaders()
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
testLacksSameOriginSecurity()
ApiMain::lacksSameOriginSecurity.
global $wgAutoloadClasses
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
testConditionalRequestHeadersOutput($conditions, $headers, $isError=false, $post=false)
Test conditional headers output provideConditionalRequestHeadersOutput.
testAssert($registered, $rights, $assert, $error)
Tests the assert={user|bot} functionality.
Definition: ApiMainTest.php:44
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null)
Does the API request and returns the result.
Definition: ApiTestCase.php:86
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2418
global $wgAutoloadLocalClasses
Definition: autoload.php:4
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1004
static provideConditionalRequestHeadersOutput()
static newFromObject($object)
Return the same object, without access restrictions.
static provideAssert()
Definition: ApiMainTest.php:24
testClassNamesInModuleManager()
Test if all classes in the main module manager exists.
Definition: ApiMainTest.php:64
This exception will be thrown when dieUsage is called to stop module execution.
Definition: ApiMain.php:1888
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310