27ec73a94c5249d435d19fe0356b763918f76b16
3 abstract class ApiFormatTestBase
extends MediaWikiTestCase
{
6 * Name of the formatter being tested
9 protected $printerName;
12 * Return general data to be encoded for testing
13 * @return array See self::testGeneralEncoding
14 * @throws BadMethodCallException
16 public static function provideGeneralEncoding() {
17 throw new BadMethodCallException( static::class . ' must implement ' . __METHOD__
);
21 * Get the formatter output for the given input data
22 * @param array $params Query parameters
23 * @param array $data Data to encode
24 * @param array $options Options. If passed a string, the string is treated
25 * as the 'class' option.
26 * - name: Format name, rather than $this->printerName
27 * - class: If set, register 'name' with this class (and 'factory', if that's set)
28 * - factory: Used with 'class' to register at runtime
29 * - returnPrinter: Return the printer object
30 * @param callable|null $factory Factory to use instead of the normal one
31 * @return string|array The string if $options['returnPrinter'] isn't set, or an array if it is:
32 * - text: Output text string
33 * - printer: ApiFormatBase
36 protected function encodeData( array $params, array $data, $options = [] ) {
37 if ( is_string( $options ) ) {
38 $options = [ 'class' => $options ];
40 $printerName = $options['name'] ??
$this->printerName
;
41 $flags = $options['flags'] ??
0;
43 $context = new RequestContext
;
44 $context->setRequest( new FauxRequest( $params, true ) );
45 $main = new ApiMain( $context );
46 if ( isset( $options['class'] ) ) {
47 $factory = $options['factory'] ??
null;
48 $main->getModuleManager()->addModule( $printerName, 'format', $options['class'], $factory );
50 $result = $main->getResult();
51 $result->addArrayType( null, 'default' );
52 foreach ( $data as $k => $v ) {
53 $result->addValue( null, $k, $v, $flags );
57 $printer = $main->createPrinterByName( $printerName );
58 $printer->initPrinter();
62 $printer->closePrinter();
63 $ret['text'] = ob_get_clean();
64 } catch ( Exception
$ex ) {
69 if ( !empty( $options['returnPrinter'] ) ) {
70 $ret['printer'] = $printer;
73 return count( $ret ) === 1 ?
$ret['text'] : $ret;
77 * @dataProvider provideGeneralEncoding
78 * @param array $data Data to be encoded
79 * @param string|Exception $expect String to expect, or exception expected to be thrown
80 * @param array $params Query parameters to set in the FauxRequest
81 * @param array $options Options to pass to self::encodeData()
83 public function testGeneralEncoding(
84 array $data, $expect, array $params = [], array $options = []
86 if ( $expect instanceof Exception
) {
87 $this->setExpectedException( get_class( $expect ), $expect->getMessage() );
88 $this->encodeData( $params, $data, $options ); // Should throw
90 $this->assertSame( $expect, $this->encodeData( $params, $data, $options ) );