Improve testing for ApiFormatBase subclasses
[lhc/web/wiklou.git] / tests / phpunit / includes / api / format / ApiFormatTestBase.php
1 <?php
2
3 abstract class ApiFormatTestBase extends MediaWikiTestCase {
4
5 /**
6 * Name of the formatter being tested
7 * @var string
8 */
9 protected $printerName;
10
11 /**
12 * Return general data to be encoded for testing
13 * @return array See self::testGeneralEncoding
14 */
15 public static function provideGeneralEncoding() {
16 throw new Exception( 'Subclass must implement ' . __METHOD__ );
17 }
18
19 /**
20 * Get the formatter output for the given input data
21 * @param array $params Query parameters
22 * @param array $data Data to encode
23 * @param string $class Printer class to use instead of the normal one
24 */
25 protected function encodeData( array $params, array $data, $class = null ) {
26 $context = new RequestContext;
27 $context->setRequest( new FauxRequest( $params, true ) );
28 $main = new ApiMain( $context );
29 if ( $class !== null ) {
30 $main->getModuleManager()->addModule( $this->printerName, 'format', $class );
31 }
32 $result = $main->getResult();
33 foreach ( $data as $k => $v ) {
34 $result->addValue( null, $k, $v );
35 }
36
37 $printer = $main->createPrinterByName( $this->printerName );
38 $printer->initPrinter();
39 $printer->execute();
40 ob_start();
41 try {
42 $printer->closePrinter();
43 return ob_get_clean();
44 } catch ( Exception $ex ) {
45 ob_end_clean();
46 throw $ex;
47 }
48 }
49
50 /**
51 * @dataProvider provideGeneralEncoding
52 */
53 public function testGeneralEncoding( array $data, $expect, array $params = array() ) {
54 if ( isset( $params['SKIP'] ) ) {
55 $this->markTestSkipped( $expect );
56 }
57 $this->assertSame( $expect, $this->encodeData( $params, $data ) );
58 }
59
60 }