3 namespace MediaWiki\Tests\Rest
;
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
;
14 * @covers \MediaWiki\Rest\Router
16 class RouterTest
extends \MediaWikiTestCase
{
18 private function createRouter( $authError = null ) {
20 [ __DIR__
. '/testRoutes.json' ],
23 new \
EmptyBagOStuff(),
24 new ResponseFactory(),
25 new StaticBasicAuthorizer( $authError ) );
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() );
35 public function testWrongMethod() {
36 $router = $this->createRouter();
37 $request = new RequestData( [
38 'uri' => new Uri( '/rest/user/joe/hello' ),
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' ) );
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
55 public static function throwHandlerFactory() {
56 return new class extends Handler
{
57 public function execute() {
58 throw new HttpException( 'Mock error', 555 );
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();
70 $data = json_decode( $body->getContents(), true );
71 $this->assertSame( 'Mock error', $data['message'] );
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();
82 $data = json_decode( $body->getContents(), true );
83 $this->assertSame( 'test-error', $data['error'] );