Merge "Exclude redirects from Special:Fewestrevisions"
[lhc/web/wiklou.git] / tests / phpunit / unit / includes / Rest / RouterTest.php
1 <?php
2
3 namespace MediaWiki\Tests\Rest;
4
5 use GuzzleHttp\Psr7\Uri;
6 use MediaWiki\Rest\BasicAccess\StaticBasicAuthorizer;
7 use MediaWiki\Rest\Handler;
8 use MediaWiki\Rest\HttpException;
9 use MediaWiki\Rest\RequestData;
10 use MediaWiki\Rest\ResponseFactory;
11 use MediaWiki\Rest\Router;
12
13 /**
14 * @covers \MediaWiki\Rest\Router
15 */
16 class RouterTest extends \MediaWikiUnitTestCase {
17 /** @return Router */
18 private function createRouter( $authError = null ) {
19 return new Router(
20 [ __DIR__ . '/testRoutes.json' ],
21 [],
22 '/rest',
23 new \EmptyBagOStuff(),
24 new ResponseFactory(),
25 new StaticBasicAuthorizer( $authError ) );
26 }
27
28 public function testPrefixMismatch() {
29 $router = $this->createRouter();
30 $request = new RequestData( [ 'uri' => new Uri( '/bogus' ) ] );
31 $response = $router->execute( $request );
32 $this->assertSame( 404, $response->getStatusCode() );
33 }
34
35 public function testWrongMethod() {
36 $router = $this->createRouter();
37 $request = new RequestData( [
38 'uri' => new Uri( '/rest/user/joe/hello' ),
39 'method' => 'OPTIONS'
40 ] );
41 $response = $router->execute( $request );
42 $this->assertSame( 405, $response->getStatusCode() );
43 $this->assertSame( 'Method Not Allowed', $response->getReasonPhrase() );
44 $this->assertSame( 'GET', $response->getHeaderLine( 'Allow' ) );
45 }
46
47 public function testNoMatch() {
48 $router = $this->createRouter();
49 $request = new RequestData( [ 'uri' => new Uri( '/rest/bogus' ) ] );
50 $response = $router->execute( $request );
51 $this->assertSame( 404, $response->getStatusCode() );
52 // TODO: add more information to the response body and test for its presence here
53 }
54
55 public static function throwHandlerFactory() {
56 return new class extends Handler {
57 public function execute() {
58 throw new HttpException( 'Mock error', 555 );
59 }
60 };
61 }
62
63 public function testException() {
64 $router = $this->createRouter();
65 $request = new RequestData( [ 'uri' => new Uri( '/rest/mock/RouterTest/throw' ) ] );
66 $response = $router->execute( $request );
67 $this->assertSame( 555, $response->getStatusCode() );
68 $body = $response->getBody();
69 $body->rewind();
70 $data = json_decode( $body->getContents(), true );
71 $this->assertSame( 'Mock error', $data['message'] );
72 }
73
74 public function testBasicAccess() {
75 $router = $this->createRouter( 'test-error' );
76 // Using the throwing handler is a way to assert that the handler is not executed
77 $request = new RequestData( [ 'uri' => new Uri( '/rest/mock/RouterTest/throw' ) ] );
78 $response = $router->execute( $request );
79 $this->assertSame( 403, $response->getStatusCode() );
80 $body = $response->getBody();
81 $body->rewind();
82 $data = json_decode( $body->getContents(), true );
83 $this->assertSame( 'test-error', $data['error'] );
84 }
85 }