3 use Wikimedia\TestingAccessWrapper
;
6 * Checks that all API modules, core and extensions, conform to the conventions:
7 * - have documentation i18n messages (the test won't catch everything since
8 * i18n messages can vary based on the wiki configuration, but it should
9 * catch many cases for forgotten i18n)
10 * - do not have inconsistencies in the parameter definitions
14 class ApiStructureTest
extends MediaWikiTestCase
{
19 /** @var array Sets of globals to test. Each array element is input to HashConfig */
20 private static $testGlobals = [
30 * Values are an array, where each array value is a permitted type. A type
31 * can be a string, which is the name of an internal type or a
32 * class/interface. Or it can be an array, in which case the value must be
33 * an array whose elements are the types given in the array (e.g., [
34 * 'string', integer' ] means an array whose entries are strings and/or
37 private static $paramTypes = [
38 // ApiBase::PARAM_DFLT => as appropriate for PARAM_TYPE
39 ApiBase
::PARAM_ISMULTI
=> [ 'boolean' ],
40 ApiBase
::PARAM_TYPE
=> [ 'string', [ 'string' ] ],
41 ApiBase
::PARAM_MAX
=> [ 'integer' ],
42 ApiBase
::PARAM_MAX2
=> [ 'integer' ],
43 ApiBase
::PARAM_MIN
=> [ 'integer' ],
44 ApiBase
::PARAM_ALLOW_DUPLICATES
=> [ 'boolean' ],
45 ApiBase
::PARAM_DEPRECATED
=> [ 'boolean' ],
46 ApiBase
::PARAM_REQUIRED
=> [ 'boolean' ],
47 ApiBase
::PARAM_RANGE_ENFORCE
=> [ 'boolean' ],
48 ApiBase
::PARAM_HELP_MSG
=> [ 'string', 'array', Message
::class ],
49 ApiBase
::PARAM_HELP_MSG_APPEND
=> [ [ 'string', 'array', Message
::class ] ],
50 ApiBase
::PARAM_HELP_MSG_INFO
=> [ [ 'array' ] ],
51 ApiBase
::PARAM_VALUE_LINKS
=> [ [ 'string' ] ],
52 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [ [ 'string', 'array', Message
::class ] ],
53 ApiBase
::PARAM_SUBMODULE_MAP
=> [ [ 'string' ] ],
54 ApiBase
::PARAM_SUBMODULE_PARAM_PREFIX
=> [ 'string' ],
55 ApiBase
::PARAM_ALL
=> [ 'boolean', 'string' ],
56 ApiBase
::PARAM_EXTRA_NAMESPACES
=> [ [ 'integer' ] ],
57 ApiBase
::PARAM_SENSITIVE
=> [ 'boolean' ],
58 ApiBase
::PARAM_DEPRECATED_VALUES
=> [ 'array' ],
59 ApiBase
::PARAM_ISMULTI_LIMIT1
=> [ 'integer' ],
60 ApiBase
::PARAM_ISMULTI_LIMIT2
=> [ 'integer' ],
61 ApiBase
::PARAM_MAX_BYTES
=> [ 'integer' ],
62 ApiBase
::PARAM_MAX_CHARS
=> [ 'integer' ],
65 // param => [ other param that must be present => required value or null ]
66 private static $paramRequirements = [
67 ApiBase
::PARAM_ALLOW_DUPLICATES
=> [ ApiBase
::PARAM_ISMULTI
=> true ],
68 ApiBase
::PARAM_ALL
=> [ ApiBase
::PARAM_ISMULTI
=> true ],
69 ApiBase
::PARAM_ISMULTI_LIMIT1
=> [
70 ApiBase
::PARAM_ISMULTI
=> true,
71 ApiBase
::PARAM_ISMULTI_LIMIT2
=> null,
73 ApiBase
::PARAM_ISMULTI_LIMIT2
=> [
74 ApiBase
::PARAM_ISMULTI
=> true,
75 ApiBase
::PARAM_ISMULTI_LIMIT1
=> null,
79 // param => type(s) allowed for this param ('array' is any array)
80 private static $paramAllowedTypes = [
81 ApiBase
::PARAM_MAX
=> [ 'integer', 'limit' ],
82 ApiBase
::PARAM_MAX2
=> 'limit',
83 ApiBase
::PARAM_MIN
=> [ 'integer', 'limit' ],
84 ApiBase
::PARAM_RANGE_ENFORCE
=> 'integer',
85 ApiBase
::PARAM_VALUE_LINKS
=> 'array',
86 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> 'array',
87 ApiBase
::PARAM_SUBMODULE_MAP
=> 'submodule',
88 ApiBase
::PARAM_SUBMODULE_PARAM_PREFIX
=> 'submodule',
89 ApiBase
::PARAM_ALL
=> 'array',
90 ApiBase
::PARAM_EXTRA_NAMESPACES
=> 'namespace',
91 ApiBase
::PARAM_DEPRECATED_VALUES
=> 'array',
92 ApiBase
::PARAM_MAX_BYTES
=> [ 'NULL', 'string', 'text', 'password' ],
93 ApiBase
::PARAM_MAX_CHARS
=> [ 'NULL', 'string', 'text', 'password' ],
96 private static $paramProhibitedTypes = [
97 ApiBase
::PARAM_ISMULTI
=> [ 'boolean', 'limit', 'upload' ],
98 ApiBase
::PARAM_ALL
=> 'namespace',
99 ApiBase
::PARAM_SENSITIVE
=> 'password',
102 private static $constantNames = null;
105 * Initialize/fetch the ApiMain instance for testing
108 private static function getMain() {
109 if ( !self
::$main ) {
110 self
::$main = new ApiMain( RequestContext
::getMain() );
111 self
::$main->getContext()->setLanguage( 'en' );
112 self
::$main->getContext()->setTitle(
113 Title
::makeTitle( NS_SPECIAL
, 'Badtitle/dummy title for ApiStructureTest' )
121 * @param Message $msg
122 * @param string $what Which message is being checked
124 private function checkMessage( $msg, $what ) {
125 $msg = ApiBase
::makeMessage( $msg, self
::getMain()->getContext() );
126 $this->assertInstanceOf( Message
::class, $msg, "$what message" );
127 $this->assertTrue( $msg->exists(), "$what message {$msg->getKey()} exists" );
131 * @dataProvider provideDocumentationExists
132 * @param string $path Module path
133 * @param array $globals Globals to set
135 public function testDocumentationExists( $path, array $globals ) {
136 $main = self
::getMain();
138 // Set configuration variables
139 $main->getContext()->setConfig( new MultiConfig( [
140 new HashConfig( $globals ),
141 RequestContext
::getMain()->getConfig(),
143 foreach ( $globals as $k => $v ) {
144 $this->setMwGlobals( "wg$k", $v );
148 $module = TestingAccessWrapper
::newFromObject( $main->getModuleFromPath( $path ) );
150 // Test messages for flags.
151 foreach ( $module->getHelpFlags() as $flag ) {
152 $this->checkMessage( "api-help-flag-$flag", "Flag $flag" );
155 // Module description messages.
156 $this->checkMessage( $module->getSummaryMessage(), 'Module summary' );
157 $this->checkMessage( $module->getExtendedDescription(), 'Module help top text' );
159 // Parameters. Lots of messages in here.
160 $params = $module->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
162 foreach ( $params as $name => $settings ) {
163 if ( !is_array( $settings ) ) {
167 // Basic description message
168 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG
] ) ) {
169 $msg = $settings[ApiBase
::PARAM_HELP_MSG
];
171 $msg = "apihelp-{$path}-param-{$name}";
173 $this->checkMessage( $msg, "Parameter $name description" );
175 // If param-per-value is in use, each value's message
176 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
] ) ) {
177 $this->assertInternalType( 'array', $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
],
178 "Parameter $name PARAM_HELP_MSG_PER_VALUE is array" );
179 $this->assertInternalType( 'array', $settings[ApiBase
::PARAM_TYPE
],
180 "Parameter $name PARAM_TYPE is array for msg-per-value mode" );
181 $valueMsgs = $settings[ApiBase
::PARAM_HELP_MSG_PER_VALUE
];
182 foreach ( $settings[ApiBase
::PARAM_TYPE
] as $value ) {
183 if ( isset( $valueMsgs[$value] ) ) {
184 $msg = $valueMsgs[$value];
186 $msg = "apihelp-{$path}-paramvalue-{$name}-{$value}";
188 $this->checkMessage( $msg, "Parameter $name value $value" );
192 // Appended messages (e.g. "disabled in miser mode")
193 if ( isset( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] ) ) {
194 $this->assertInternalType( 'array', $settings[ApiBase
::PARAM_HELP_MSG_APPEND
],
195 "Parameter $name PARAM_HELP_MSG_APPEND is array" );
196 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_APPEND
] as $i => $msg ) {
197 $this->checkMessage( $msg, "Parameter $name HELP_MSG_APPEND #$i" );
201 // Info tags (e.g. "only usable in mode 1") are typically shared by
202 // several parameters, so accumulate them and test them later.
203 if ( !empty( $settings[ApiBase
::PARAM_HELP_MSG_INFO
] ) ) {
204 foreach ( $settings[ApiBase
::PARAM_HELP_MSG_INFO
] as $i ) {
205 $tags[array_shift( $i )] = 1;
210 // Info tags (e.g. "only usable in mode 1") accumulated above
211 foreach ( $tags as $tag => $dummy ) {
212 $this->checkMessage( "apihelp-{$path}-paraminfo-{$tag}", "HELP_MSG_INFO tag $tag" );
215 // Messages for examples.
216 foreach ( $module->getExamplesMessages() as $qs => $msg ) {
217 $this->assertStringStartsNotWith( 'api.php?', $qs,
218 "Query string must not begin with 'api.php?'" );
219 $this->checkMessage( $msg, "Example $qs" );
223 public static function provideDocumentationExists() {
224 $main = self
::getMain();
225 $paths = self
::getSubModulePaths( $main->getModuleManager() );
226 array_unshift( $paths, $main->getModulePath() );
229 foreach ( $paths as $path ) {
230 foreach ( self
::$testGlobals as $globals ) {
232 foreach ( $globals as $k => $v ) {
233 $g[] = "$k=" . var_export( $v, 1 );
235 $k = "Module $path with " . implode( ', ', $g );
236 $ret[$k] = [ $path, $globals ];
243 * @dataProvider provideParameterConsistency
244 * @param string $path
246 public function testParameterConsistency( $path ) {
247 $main = self
::getMain();
248 $module = TestingAccessWrapper
::newFromObject( $main->getModuleFromPath( $path ) );
250 $paramsPlain = $module->getFinalParams();
251 $paramsForHelp = $module->getFinalParams( ApiBase
::GET_VALUES_FOR_HELP
);
253 // avoid warnings about empty tests when no parameter needs to be checked
254 $this->assertTrue( true );
256 if ( self
::$constantNames === null ) {
257 self
::$constantNames = [];
259 foreach ( ( new ReflectionClass( 'ApiBase' ) )->getConstants() as $key => $val ) {
260 if ( substr( $key, 0, 6 ) === 'PARAM_' ) {
261 self
::$constantNames[$val] = $key;
266 foreach ( [ $paramsPlain, $paramsForHelp ] as $params ) {
267 foreach ( $params as $param => $config ) {
268 if ( !is_array( $config ) ) {
269 $config = [ ApiBase
::PARAM_DFLT
=> $config ];
271 if ( !isset( $config[ApiBase
::PARAM_TYPE
] ) ) {
272 $config[ApiBase
::PARAM_TYPE
] = isset( $config[ApiBase
::PARAM_DFLT
] )
273 ?
gettype( $config[ApiBase
::PARAM_DFLT
] )
277 foreach ( self
::$paramTypes as $key => $types ) {
278 if ( !isset( $config[$key] ) ) {
281 $keyName = self
::$constantNames[$key];
282 $this->validateType( $types, $config[$key], $param, $keyName );
285 foreach ( self
::$paramRequirements as $key => $required ) {
286 if ( !isset( $config[$key] ) ) {
289 foreach ( $required as $requireKey => $requireVal ) {
290 $this->assertArrayHasKey( $requireKey, $config,
291 "$param: When " . self
::$constantNames[$key] . " is set, " .
292 self
::$constantNames[$requireKey] . " must also be set" );
293 if ( $requireVal !== null ) {
294 $this->assertSame( $requireVal, $config[$requireKey],
295 "$param: When " . self
::$constantNames[$key] . " is set, " .
296 self
::$constantNames[$requireKey] . " must equal " .
297 var_export( $requireVal, true ) );
302 foreach ( self
::$paramAllowedTypes as $key => $allowedTypes ) {
303 if ( !isset( $config[$key] ) ) {
307 $actualType = is_array( $config[ApiBase
::PARAM_TYPE
] )
308 ?
'array' : $config[ApiBase
::PARAM_TYPE
];
310 $this->assertContains(
312 (array)$allowedTypes,
313 "$param: " . self
::$constantNames[$key] .
314 " can only be used with PARAM_TYPE " .
315 implode( ', ', (array)$allowedTypes )
319 foreach ( self
::$paramProhibitedTypes as $key => $prohibitedTypes ) {
320 if ( !isset( $config[$key] ) ) {
324 $actualType = is_array( $config[ApiBase
::PARAM_TYPE
] )
325 ?
'array' : $config[ApiBase
::PARAM_TYPE
];
327 $this->assertNotContains(
329 (array)$prohibitedTypes,
330 "$param: " . self
::$constantNames[$key] .
331 " cannot be used with PARAM_TYPE " .
332 implode( ', ', (array)$prohibitedTypes )
336 if ( isset( $config[ApiBase
::PARAM_DFLT
] ) ) {
338 isset( $config[ApiBase
::PARAM_REQUIRED
] ) &&
339 $config[ApiBase
::PARAM_REQUIRED
],
340 "$param: A required parameter cannot have a default" );
342 $this->validateDefault( $param, $config );
345 if ( $config[ApiBase
::PARAM_TYPE
] === 'limit' ) {
347 isset( $config[ApiBase
::PARAM_MAX
] ) &&
348 isset( $config[ApiBase
::PARAM_MAX2
] ),
349 "$param: PARAM_MAX and PARAM_MAX2 are required for limits"
351 $this->assertGreaterThanOrEqual(
352 $config[ApiBase
::PARAM_MAX
],
353 $config[ApiBase
::PARAM_MAX2
],
354 "$param: PARAM_MAX cannot be greater than PARAM_MAX2"
359 isset( $config[ApiBase
::PARAM_MIN
] ) &&
360 isset( $config[ApiBase
::PARAM_MAX
] )
362 $this->assertGreaterThanOrEqual(
363 $config[ApiBase
::PARAM_MIN
],
364 $config[ApiBase
::PARAM_MAX
],
365 "$param: PARAM_MIN cannot be greater than PARAM_MAX"
369 if ( isset( $config[ApiBase
::PARAM_RANGE_ENFORCE
] ) ) {
371 isset( $config[ApiBase
::PARAM_MIN
] ) ||
372 isset( $config[ApiBase
::PARAM_MAX
] ),
373 "$param: PARAM_RANGE_ENFORCE can only be set together with " .
374 "PARAM_MIN or PARAM_MAX"
378 if ( isset( $config[ApiBase
::PARAM_DEPRECATED_VALUES
] ) ) {
379 foreach ( $config[ApiBase
::PARAM_DEPRECATED_VALUES
] as $key => $unused ) {
380 $this->assertContains( $key, $config[ApiBase
::PARAM_TYPE
],
381 "$param: Deprecated value \"$key\" is not allowed, " .
382 "how can it be deprecated?" );
387 isset( $config[ApiBase
::PARAM_ISMULTI_LIMIT1
] ) ||
388 isset( $config[ApiBase
::PARAM_ISMULTI_LIMIT2
] )
390 $this->assertGreaterThanOrEqual( 0, $config[ApiBase
::PARAM_ISMULTI_LIMIT1
],
391 "$param: PARAM_ISMULTI_LIMIT1 cannot be negative" );
392 // Zero for both doesn't make sense, but you could have
394 $this->assertGreaterThanOrEqual( 1, $config[ApiBase
::PARAM_ISMULTI_LIMIT2
],
395 "$param: PARAM_ISMULTI_LIMIT2 cannot be negative or zero" );
396 $this->assertGreaterThanOrEqual(
397 $config[ApiBase
::PARAM_ISMULTI_LIMIT1
],
398 $config[ApiBase
::PARAM_ISMULTI_LIMIT2
],
399 "$param: PARAM_ISMULTI limit cannot be smaller for users with " .
400 "apihighlimits rights" );
403 if ( isset( $config[ApiBase
::PARAM_MAX_BYTES
] ) ) {
404 $this->assertGreaterThanOrEqual( 1, $config[ApiBase
::PARAM_MAX_BYTES
],
405 "$param: PARAM_MAX_BYTES cannot be negative or zero" );
408 if ( isset( $config[ApiBase
::PARAM_MAX_CHARS
] ) ) {
409 $this->assertGreaterThanOrEqual( 1, $config[ApiBase
::PARAM_MAX_CHARS
],
410 "$param: PARAM_MAX_CHARS cannot be negative or zero" );
414 isset( $config[ApiBase
::PARAM_MAX_BYTES
] ) &&
415 isset( $config[ApiBase
::PARAM_MAX_CHARS
] )
417 // Length of a string in chars is always <= length in bytes,
418 // so PARAM_MAX_CHARS is pointless if > PARAM_MAX_BYTES
419 $this->assertGreaterThanOrEqual(
420 $config[ApiBase
::PARAM_MAX_CHARS
],
421 $config[ApiBase
::PARAM_MAX_BYTES
],
422 "$param: PARAM_MAX_BYTES cannot be less than PARAM_MAX_CHARS"
430 * Throws if $value does not match one of the types specified in $types.
432 * @param array $types From self::$paramTypes array
433 * @param mixed $value Value to check
434 * @param string $param Name of param we're checking, for error messages
435 * @param string $desc Description for error messages
437 private function validateType( $types, $value, $param, $desc ) {
438 if ( count( $types ) === 1 ) {
439 // Only one type allowed
440 if ( is_string( $types[0] ) ) {
441 $this->assertType( $types[0], $value, "$param: $desc type" );
443 // Array whose values have specified types, recurse
444 $this->assertInternalType( 'array', $value, "$param: $desc type" );
445 foreach ( $value as $subvalue ) {
446 $this->validateType( $types[0], $subvalue, $param, "$desc value" );
451 foreach ( $types as $type ) {
452 if ( is_string( $type ) ) {
453 if ( class_exists( $type ) ||
interface_exists( $type ) ) {
454 if ( $value instanceof $type ) {
458 if ( gettype( $value ) === $type ) {
463 // Array whose values have specified types, recurse
465 $this->validateType( [ $type ], $value, $param, "$desc type" );
466 // Didn't throw, so we're good
468 } catch ( Exception
$unused ) {
472 // Doesn't match any of them
473 $this->fail( "$param: $desc has incorrect type" );
478 * Asserts that $default is a valid default for $type.
480 * @param string $param Name of param, for error messages
481 * @param array $config Array of configuration options for this parameter
483 private function validateDefault( $param, $config ) {
484 $type = $config[ApiBase
::PARAM_TYPE
];
485 $default = $config[ApiBase
::PARAM_DFLT
];
487 if ( !empty( $config[ApiBase
::PARAM_ISMULTI
] ) ) {
488 if ( $default === '' ) {
489 // The empty array is fine
492 $defaults = explode( '|', $default );
493 $config[ApiBase
::PARAM_ISMULTI
] = false;
494 foreach ( $defaults as $defaultValue ) {
495 // Only allow integers in their simplest form with no leading
496 // or trailing characters etc.
497 if ( $type === 'integer' && $defaultValue === (string)(int)$defaultValue ) {
498 $defaultValue = (int)$defaultValue;
500 $config[ApiBase
::PARAM_DFLT
] = $defaultValue;
501 $this->validateDefault( $param, $config );
507 $this->assertFalse( $default,
508 "$param: Boolean params may only default to false" );
512 $this->assertInternalType( 'integer', $default,
513 "$param: Default $default is not an integer" );
517 if ( $default === 'max' ) {
520 $this->assertInternalType( 'integer', $default,
521 "$param: Default $default is neither an integer nor \"max\"" );
525 $validValues = MWNamespace
::getValidNamespaces();
527 isset( $config[ApiBase
::PARAM_EXTRA_NAMESPACES
] ) &&
528 is_array( $config[ApiBase
::PARAM_EXTRA_NAMESPACES
] )
530 $validValues = array_merge(
532 $config[ApiBase
::PARAM_EXTRA_NAMESPACES
]
535 $this->assertContains( $default, $validValues,
536 "$param: Default $default is not a valid namespace" );
545 $this->assertInternalType( 'string', $default,
546 "$param: Default $default is not a string" );
550 if ( $default === 'now' ) {
553 $this->assertNotFalse( wfTimestamp( TS_MW
, $default ),
554 "$param: Default $default is not a valid timestamp" );
558 // @todo Should we make user validation a public static method
559 // in ApiBase() or something so we don't have to resort to
560 // this? Or in User for that matter.
561 $wrapper = TestingAccessWrapper
::newFromObject( new ApiMain() );
563 $wrapper->validateUser( $default, '' );
564 } catch ( ApiUsageException
$e ) {
565 $this->fail( "$param: Default $default is not a valid username/IP address" );
570 if ( is_array( $type ) ) {
571 $this->assertContains( $default, $type,
572 "$param: Default $default is not any of " .
573 implode( ', ', $type ) );
575 $this->fail( "Unrecognized type $type" );
581 * @return array List of API module paths to test
583 public static function provideParameterConsistency() {
584 $main = self
::getMain();
585 $paths = self
::getSubModulePaths( $main->getModuleManager() );
586 array_unshift( $paths, $main->getModulePath() );
589 foreach ( $paths as $path ) {
596 * Return paths of all submodules in an ApiModuleManager, recursively
597 * @param ApiModuleManager $manager
600 protected static function getSubModulePaths( ApiModuleManager
$manager ) {
602 foreach ( $manager->getNames() as $name ) {
603 $module = $manager->getModule( $name );
604 $paths[] = $module->getModulePath();
605 $subManager = $module->getModuleManager();
607 $paths = array_merge( $paths, self
::getSubModulePaths( $subManager ) );