MediaWiki REL1_32
ApiOptionsTest.php
Go to the documentation of this file.
1<?php
2
11
13 private $mUserMock;
15 private $mTested;
16 private $mSession;
18 private $mContext;
19
20 private static $Success = [ 'options' => 'success' ];
21
22 protected function setUp() {
23 parent::setUp();
24
25 $this->mUserMock = $this->getMockBuilder( User::class )
26 ->disableOriginalConstructor()
27 ->getMock();
28
29 // Set up groups and rights
30 $this->mUserMock->expects( $this->any() )
31 ->method( 'getEffectiveGroups' )->will( $this->returnValue( [ '*', 'user' ] ) );
32 $this->mUserMock->expects( $this->any() )
33 ->method( 'isAllowedAny' )->will( $this->returnValue( true ) );
34
35 // Set up callback for User::getOptionKinds
36 $this->mUserMock->expects( $this->any() )
37 ->method( 'getOptionKinds' )->will( $this->returnCallback( [ $this, 'getOptionKinds' ] ) );
38
39 // No actual DB data
40 $this->mUserMock->expects( $this->any() )
41 ->method( 'getInstanceForUpdate' )->will( $this->returnValue( $this->mUserMock ) );
42
43 // Needs to return something
44 $this->mUserMock->method( 'getOptions' )
45 ->willReturn( [] );
46
47 // Create a new context
48 $this->mContext = new DerivativeContext( new RequestContext() );
49 $this->mContext->getContext()->setTitle( Title::newFromText( 'Test' ) );
50 $this->mContext->setUser( $this->mUserMock );
51
52 $main = new ApiMain( $this->mContext );
53
54 // Empty session
55 $this->mSession = [];
56
57 $this->mTested = new ApiOptions( $main, 'options' );
58
59 $this->mergeMwGlobalArrayValue( 'wgHooks', [
60 'GetPreferences' => [
61 [ $this, 'hookGetPreferences' ]
62 ]
63 ] );
64 $this->mergeMwGlobalArrayValue( 'wgDefaultUserOptions', [
65 'testradio' => 'option1',
66 ] );
67 // Workaround for static caching in User::getDefaultOptions()
68 $this->setContentLang( Language::factory( 'qqq' ) );
69 }
70
71 public function hookGetPreferences( $user, &$preferences ) {
72 $preferences = [];
73
74 foreach ( [ 'name', 'willBeNull', 'willBeEmpty', 'willBeHappy' ] as $k ) {
75 $preferences[$k] = [
76 'type' => 'text',
77 'section' => 'test',
78 'label' => "\u{00A0}",
79 ];
80 }
81
82 $preferences['testmultiselect'] = [
83 'type' => 'multiselect',
84 'options' => [
85 'Test' => [
86 '<span dir="auto">Some HTML here for option 1</span>' => 'opt1',
87 '<span dir="auto">Some HTML here for option 2</span>' => 'opt2',
88 '<span dir="auto">Some HTML here for option 3</span>' => 'opt3',
89 '<span dir="auto">Some HTML here for option 4</span>' => 'opt4',
90 ],
91 ],
92 'section' => 'test',
93 'label' => "\u{00A0}",
94 'prefix' => 'testmultiselect-',
95 'default' => [],
96 ];
97
98 $preferences['testradio'] = [
99 'type' => 'radio',
100 'options' => [ 'Option 1' => 'option1', 'Option 2' => 'option2' ],
101 'section' => 'test',
102 ];
103 }
104
111 public function getOptionKinds( IContextSource $context, $options = null ) {
112 // Match with above.
113 $kinds = [
114 'name' => 'registered',
115 'willBeNull' => 'registered',
116 'willBeEmpty' => 'registered',
117 'willBeHappy' => 'registered',
118 'testradio' => 'registered',
119 'testmultiselect-opt1' => 'registered-multiselect',
120 'testmultiselect-opt2' => 'registered-multiselect',
121 'testmultiselect-opt3' => 'registered-multiselect',
122 'testmultiselect-opt4' => 'registered-multiselect',
123 'special' => 'special',
124 ];
125
126 if ( $options === null ) {
127 return $kinds;
128 }
129
130 $mapping = [];
131 foreach ( $options as $key => $value ) {
132 if ( isset( $kinds[$key] ) ) {
133 $mapping[$key] = $kinds[$key];
134 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
135 $mapping[$key] = 'userjs';
136 } else {
137 $mapping[$key] = 'unused';
138 }
139 }
140
141 return $mapping;
142 }
143
144 private function getSampleRequest( $custom = [] ) {
145 $request = [
146 'token' => '123ABC',
147 'change' => null,
148 'optionname' => null,
149 'optionvalue' => null,
150 ];
151
152 return array_merge( $request, $custom );
153 }
154
155 private function executeQuery( $request ) {
156 $this->mContext->setRequest( new FauxRequest( $request, true, $this->mSession ) );
157 $this->mTested->execute();
158
159 return $this->mTested->getResult()->getResultData( null, [ 'Strip' => 'all' ] );
160 }
161
165 public function testNoToken() {
166 $request = $this->getSampleRequest( [ 'token' => null ] );
167
168 $this->executeQuery( $request );
169 }
170
171 public function testAnon() {
172 $this->mUserMock->expects( $this->once() )
173 ->method( 'isAnon' )
174 ->will( $this->returnValue( true ) );
175
176 try {
177 $request = $this->getSampleRequest();
178
179 $this->executeQuery( $request );
180 } catch ( ApiUsageException $e ) {
181 $this->assertTrue( ApiTestCase::apiExceptionHasCode( $e, 'notloggedin' ) );
182 return;
183 }
184 $this->fail( "ApiUsageException was not thrown" );
185 }
186
187 public function testNoOptionname() {
188 try {
189 $request = $this->getSampleRequest( [ 'optionvalue' => '1' ] );
190
191 $this->executeQuery( $request );
192 } catch ( ApiUsageException $e ) {
193 $this->assertTrue( ApiTestCase::apiExceptionHasCode( $e, 'nooptionname' ) );
194 return;
195 }
196 $this->fail( "ApiUsageException was not thrown" );
197 }
198
199 public function testNoChanges() {
200 $this->mUserMock->expects( $this->never() )
201 ->method( 'resetOptions' );
202
203 $this->mUserMock->expects( $this->never() )
204 ->method( 'setOption' );
205
206 $this->mUserMock->expects( $this->never() )
207 ->method( 'saveSettings' );
208
209 try {
210 $request = $this->getSampleRequest();
211
212 $this->executeQuery( $request );
213 } catch ( ApiUsageException $e ) {
214 $this->assertTrue( ApiTestCase::apiExceptionHasCode( $e, 'nochanges' ) );
215 return;
216 }
217 $this->fail( "ApiUsageException was not thrown" );
218 }
219
220 public function testReset() {
221 $this->mUserMock->expects( $this->once() )
222 ->method( 'resetOptions' )
223 ->with( $this->equalTo( [ 'all' ] ) );
224
225 $this->mUserMock->expects( $this->never() )
226 ->method( 'setOption' );
227
228 $this->mUserMock->expects( $this->once() )
229 ->method( 'saveSettings' );
230
231 $request = $this->getSampleRequest( [ 'reset' => '' ] );
232
233 $response = $this->executeQuery( $request );
234
235 $this->assertEquals( self::$Success, $response );
236 }
237
238 public function testResetKinds() {
239 $this->mUserMock->expects( $this->once() )
240 ->method( 'resetOptions' )
241 ->with( $this->equalTo( [ 'registered' ] ) );
242
243 $this->mUserMock->expects( $this->never() )
244 ->method( 'setOption' );
245
246 $this->mUserMock->expects( $this->once() )
247 ->method( 'saveSettings' );
248
249 $request = $this->getSampleRequest( [ 'reset' => '', 'resetkinds' => 'registered' ] );
250
251 $response = $this->executeQuery( $request );
252
253 $this->assertEquals( self::$Success, $response );
254 }
255
256 public function testResetChangeOption() {
257 $this->mUserMock->expects( $this->once() )
258 ->method( 'resetOptions' );
259
260 $this->mUserMock->expects( $this->exactly( 2 ) )
261 ->method( 'setOption' )
262 ->withConsecutive(
263 [ $this->equalTo( 'willBeHappy' ), $this->equalTo( 'Happy' ) ],
264 [ $this->equalTo( 'name' ), $this->equalTo( 'value' ) ]
265 );
266
267 $this->mUserMock->expects( $this->once() )
268 ->method( 'saveSettings' );
269
270 $args = [
271 'reset' => '',
272 'change' => 'willBeHappy=Happy',
273 'optionname' => 'name',
274 'optionvalue' => 'value'
275 ];
276
277 $response = $this->executeQuery( $this->getSampleRequest( $args ) );
278
279 $this->assertEquals( self::$Success, $response );
280 }
281
288 public function testOptionManupulation( array $params, array $setOptions, array $result = null,
289 $message = ''
290 ) {
291 $this->mUserMock->expects( $this->never() )
292 ->method( 'resetOptions' );
293
294 $this->mUserMock->expects( $this->exactly( count( $setOptions ) ) )
295 ->method( 'setOption' )
296 ->withConsecutive( ...$setOptions );
297
298 if ( $setOptions ) {
299 $this->mUserMock->expects( $this->once() )
300 ->method( 'saveSettings' );
301 } else {
302 $this->mUserMock->expects( $this->never() )
303 ->method( 'saveSettings' );
304 }
305
306 $request = $this->getSampleRequest( $params );
307 $response = $this->executeQuery( $request );
308
309 if ( !$result ) {
311 }
312 $this->assertEquals( $result, $response, $message );
313 }
314
315 public function provideOptionManupulation() {
316 return [
317 [
318 [ 'change' => 'userjs-option=1' ],
319 [ [ 'userjs-option', '1' ] ],
320 null,
321 'Setting userjs options',
322 ],
323 [
324 [ 'change' => 'willBeNull|willBeEmpty=|willBeHappy=Happy' ],
325 [
326 [ 'willBeNull', null ],
327 [ 'willBeEmpty', '' ],
328 [ 'willBeHappy', 'Happy' ],
329 ],
330 null,
331 'Basic option setting',
332 ],
333 [
334 [ 'change' => 'testradio=option2' ],
335 [ [ 'testradio', 'option2' ] ],
336 null,
337 'Changing radio options',
338 ],
339 [
340 [ 'change' => 'testradio' ],
341 [ [ 'testradio', null ] ],
342 null,
343 'Resetting radio options',
344 ],
345 [
346 [ 'change' => 'unknownOption=1' ],
347 [],
348 [
349 'options' => 'success',
350 'warnings' => [
351 'options' => [
352 'warnings' => "Validation error for \"unknownOption\": not a valid preference."
353 ],
354 ],
355 ],
356 'Unrecognized options should be rejected',
357 ],
358 [
359 [ 'change' => 'special=1' ],
360 [],
361 [
362 'options' => 'success',
363 'warnings' => [
364 'options' => [
365 'warnings' => "Validation error for \"special\": cannot be set by this module."
366 ]
367 ]
368 ],
369 'Refuse setting special options',
370 ],
371 [
372 [
373 'change' => 'testmultiselect-opt1=1|testmultiselect-opt2|'
374 . 'testmultiselect-opt3=|testmultiselect-opt4=0'
375 ],
376 [
377 [ 'testmultiselect-opt1', true ],
378 [ 'testmultiselect-opt2', null ],
379 [ 'testmultiselect-opt3', false ],
380 [ 'testmultiselect-opt4', false ],
381 ],
382 null,
383 'Setting multiselect options',
384 ],
385 [
386 [ 'optionname' => 'name', 'optionvalue' => 'value' ],
387 [ [ 'name', 'value' ] ],
388 null,
389 'Setting options via optionname/optionvalue'
390 ],
391 [
392 [ 'optionname' => 'name' ],
393 [ [ 'name', null ] ],
394 null,
395 'Resetting options via optionname without optionvalue',
396 ],
397 ];
398 }
399}
if( $line===false) $args
Definition cdb.php:64
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:41
API Database medium.
testNoToken()
ApiUsageException.
testOptionManupulation(array $params, array $setOptions, array $result=null, $message='')
provideOptionManupulation
getOptionKinds(IContextSource $context, $options=null)
getSampleRequest( $custom=[])
DerivativeContext $mContext
hookGetPreferences( $user, &$preferences)
PHPUnit_Framework_MockObject_MockObject $mUserMock
executeQuery( $request)
ApiOptions $mTested
API module that facilitates the changing of user's preferences.
static apiExceptionHasCode(ApiUsageException $ex, $code)
Exception used to abort API execution with an error.
An IContextSource implementation which will inherit context from another source but allow individual ...
WebRequest clone which takes values from a provided array.
Base class that store and restore the Language objects.
mergeMwGlobalArrayValue( $name, $values)
Merges the given values into a MW global array variable.
Group all the pieces relevant to the context of a request into one instance.
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
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2880
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:2042
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 & $options
Definition hooks.txt:2050
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition hooks.txt:2885
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:2055
this hook is for auditing only $response
Definition hooks.txt:813
processing should stop and the error should be shown to the user * false
Definition hooks.txt:187
returning false will NOT prevent logging $e
Definition hooks.txt:2226
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:37
Interface for objects which can provide a MediaWiki context on request.
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$params