Debian Codegraph @

tests/phpunit/unit/includes/Rest/Module/SpecBasedModuleTest.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Tests\Rest\Module;
4
5 use GuzzleHttp\Psr7\Uri;
6 use MediaWiki\MainConfigNames;
7 use MediaWiki\Rest\BasicAccess\StaticBasicAuthorizer;
8 use MediaWiki\Rest\Module\SpecBasedModule;
9 use MediaWiki\Rest\Reporter\ErrorReporter;
10 use MediaWiki\Rest\RequestData;
11 use MediaWiki\Rest\RequestInterface;
12 use MediaWiki\Rest\ResponseFactory;
13 use MediaWiki\Rest\Validator\Validator;
14 use MediaWiki\Tests\Rest\RestTestTrait;
15 use MediaWiki\Tests\Unit\DummyServicesTrait;
16 use PHPUnit\Framework\MockObject\MockObject;
17 use Psr\Log\NullLogger;
18 use RuntimeException;
19 use Throwable;
20 use UDPTransport;
21 use Wikimedia\Stats\OutputFormats;
22 use Wikimedia\Stats\StatsCache;
23 use Wikimedia\Stats\StatsFactory;
24
25 /**
26 * @covers \MediaWiki\Rest\Module\SpecBasedModule
27 */
28 class SpecBasedModuleTest extends \MediaWikiUnitTestCase {
29 use RestTestTrait;
30 use DummyServicesTrait;
31
32 private const CANONICAL_SERVER = 'https://wiki.example.com';
33 private const INTERNAL_SERVER = 'http://api.local:8080';
34
35 /** @var Throwable[] */
36 private $reportedErrors = [];
37
38 /**
39 * @param RequestInterface $request
40 * @param string|null $authError
41 *
42 * @return SpecBasedModule
43 */
44 private function createOpenApiModule(
45 RequestInterface $request,
46 $authError = null
47 ) {
48 $specFile = __DIR__ . '/moduleTestRoutes.json';
49
50 /** @var MockObject|ErrorReporter $mockErrorReporter */
51 $mockErrorReporter = $this->createNoOpMock( ErrorReporter::class, [ 'reportError' ] );
52 $mockErrorReporter->method( 'reportError' )
53 ->willReturnCallback( function ( $e ) {
54 $this->reportedErrors[] = $e;
55 } );
56
57 $config = [
58 MainConfigNames::CanonicalServer => self::CANONICAL_SERVER,
59 MainConfigNames::InternalServer => self::INTERNAL_SERVER,
60 MainConfigNames::RestPath => '/rest',
61 ];
62
63 $auth = new StaticBasicAuthorizer( $authError );
64 $objectFactory = $this->getDummyObjectFactory();
65
66 $authority = $this->mockAnonUltimateAuthority();
67 $validator = new Validator( $objectFactory, $request, $authority );
68
69 $router = $this->newRouter( [
70 'routeFiles' => [],
71 'request' => $request,
72 'config' => $config,
73 'errorReporter' => $mockErrorReporter,
74 'basicAuth' => $auth,
75 'validator' => $validator
76 ] );
77
78 $responseFactory = new ResponseFactory( [] );
79 $responseFactory->setShowExceptionDetails( true );
80
81 $module = new SpecBasedModule(
82 $specFile,
83 $router,
84 'test.v1',
85 $responseFactory,
86 $auth,
87 $objectFactory,
88 $validator,
89 $mockErrorReporter
90 );
91
92 return $module;
93 }
94
95 private function createMockStatsFactory( string $expectedPattern ): StatsFactory {
96 $statsCache = new StatsCache();
97 $emitter = OutputFormats::getNewEmitter(
98 'mediawiki',
99 $statsCache,
100 OutputFormats::getNewFormatter( OutputFormats::DOGSTATSD )
101 );
102
103 $transport = $this->createMock( UDPTransport::class );
104
105 $transport->expects( $this->once() )->method( "emit" )
106 ->with( $this->matchesRegularExpression( $expectedPattern ) );
107
108 $emitter = $emitter->withTransport( $transport );
109 return new StatsFactory( $statsCache, $emitter, new NullLogger );
110 }
111
112 public function testHandlerConfig() {
113 $request = new RequestData( [
114 'uri' => new Uri( '/rest/test.v1/ModuleTest/hello/you' ),
115 ] );
116 $module = $this->createOpenApiModule( $request );
117
118 $stats = $this->createMockStatsFactory(
119 '/^mediawiki\.rest_api_latency_seconds:\d+\.\d+\|ms\|#path:test_v1_ModuleTest_hello_name,method:GET,status:200\n/'
120 );
121 $module->setStats( $stats );
122
123 $response = $module->execute( '/ModuleTest/hello/you', $request );
124 $stats->flush();
125
126 $this->assertSame( 200, $response->getStatusCode(), (string)$response->getBody() );
127
128 // "hi!" comes from the rout definition, the default is 'Hello!'.
129 $data = json_decode( $response->getBody(), true );
130 $this->assertSame( 'hi!', $data['message'] );
131 }
132
133 public function testWrongMethod() {
134 $request = new RequestData( [
135 'uri' => new Uri( '/rest/test.v1/ModuleTest/hello/you' ),
136 'method' => 'TRACE'
137 ] );
138 $module = $this->createOpenApiModule( $request );
139 $response = $module->execute( '/ModuleTest/hello/you', $request );
140 $this->assertSame( 405, $response->getStatusCode() );
141 $this->assertSame( 'Method Not Allowed', $response->getReasonPhrase() );
142 $this->assertSame( 'HEAD, GET', $response->getHeaderLine( 'Allow' ) );
143 }
144
145 public function testHeadToGet() {
146 $request = new RequestData( [
147 'uri' => new Uri( '/rest/test.v1/ModuleTest/hello/you' ),
148 'method' => 'HEAD'
149 ] );
150 $module = $this->createOpenApiModule( $request );
151 $response = $module->execute( '/ModuleTest/hello/you', $request );
152 $this->assertSame( 200, $response->getStatusCode() );
153 }
154
155 public function testRedirect() {
156 $request = new RequestData( [
157 'uri' => new Uri( '/rest/test.v1/ModuleTest/HELLO/you' )
158 ] );
159 $module = $this->createOpenApiModule( $request );
160 $response = $module->execute( '/ModuleTest/HELLO/you', $request );
161 $this->assertSame(
162 308,
163 $response->getStatusCode(),
164 (string)$response->getBody()
165 );
166 }
167
168 public function testNoMatch() {
169 $request = new RequestData( [ 'uri' => new Uri( '/rest/test.v1/Bogus' ) ] );
170 $module = $this->createOpenApiModule( $request );
171 $response = $module->execute( '/Bogus', $request );
172 $this->assertSame( 404, $response->getStatusCode() );
173 // TODO: add more information to the response body and test for its presence here
174 }
175
176 public function testHttpException() {
177 $request = new RequestData( [ 'uri' => new Uri( '/rest/test.v1/ModuleTest/throw' ) ] );
178 $module = $this->createOpenApiModule( $request );
179
180 $stats = $this->createMockStatsFactory(
181 '/^mediawiki\.rest_api_errors_total:1|ms\|#path:test_v1_ModuleTest_throw,method:GET,status:555\n/'
182 );
183 $module->setStats( $stats );
184
185 $response = $module->execute( '/ModuleTest/throw', $request );
186 $stats->flush();
187
188 $this->assertSame( 555, $response->getStatusCode() );
189 $body = $response->getBody();
190 $body->rewind();
191 $data = json_decode( $body->getContents(), true );
192 $this->assertSame( 'Mock error', $data['message'] );
193 }
194
195 public function testFatalException() {
196 $request = new RequestData( [ 'uri' => new Uri( '/rest/test.v1/ModuleTest/fatal' ) ] );
197 $module = $this->createOpenApiModule( $request );
198 $response = $module->execute( '/ModuleTest/fatal', $request );
199 $this->assertSame( 500, $response->getStatusCode() );
200 $body = $response->getBody();
201 $body->rewind();
202 $data = json_decode( $body->getContents(), true );
203 $this->assertStringContainsString( 'RuntimeException', $data['message'] );
204 $this->assertNotEmpty( $this->reportedErrors );
205 $this->assertInstanceOf( RuntimeException::class, $this->reportedErrors[0] );
206 }
207
208 public function testRedirectException() {
209 $request = new RequestData( [ 'uri' => new Uri( '/rest/test.v1/ModuleTest/throwRedirect' ) ] );
210 $module = $this->createOpenApiModule( $request );
211 $response = $module->execute( '/ModuleTest/throwRedirect', $request );
212 $this->assertSame( 301, $response->getStatusCode() );
213 $this->assertSame( 'http://example.com', $response->getHeaderLine( 'Location' ) );
214 }
215
216 public function testResponseException() {
217 $request = new RequestData( [ 'uri' => new Uri( '/rest/test.v1/ModuleTest/throwWrapped' ) ] );
218 $module = $this->createOpenApiModule( $request );
219 $response = $module->execute( '/ModuleTest/throwWrapped', $request );
220 $this->assertSame( 200, $response->getStatusCode() );
221 }
222
223 public function testBasicAccess() {
224 // Using the throwing handler is a way to assert that the handler is not executed
225 $request = new RequestData( [ 'uri' => new Uri( '/rest/test.v1/ModuleTest/throw' ) ] );
226 $module = $this->createOpenApiModule( $request, 'test-error', [] );
227 $response = $module->execute( '/ModuleTest/throw', $request );
228 $this->assertSame( 403, $response->getStatusCode() );
229 $body = $response->getBody();
230 $body->rewind();
231 $data = json_decode( $body->getContents(), true );
232 $this->assertSame( 'test-error', $data['error'] );
233 }
234
235 public function testOpenApiInfo() {
236 $request = new RequestData( [ 'uri' => new Uri( '/rest/test.v1/ModuleTest/throwWrapped' ) ] );
237 $module = $this->createOpenApiModule( $request );
238
239 $info = $module->getOpenApiInfo();
240 $this->assertSame( 'test', $info['title'] );
241 $this->assertSame( '1.0', $info['version'] );
242 }
243 }