1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
|
<?php
namespace MediaWiki\Tests\Rest;
use GuzzleHttp\Psr7\Uri;
use MediaWiki\Config\ServiceOptions;
use MediaWiki\MainConfigNames;
use MediaWiki\Rest\BasicAccess\StaticBasicAuthorizer;
use MediaWiki\Rest\CorsUtils;
use MediaWiki\Rest\Handler;
use MediaWiki\Rest\HttpException;
use MediaWiki\Rest\RedirectException;
use MediaWiki\Rest\Reporter\ErrorReporter;
use MediaWiki\Rest\RequestData;
use MediaWiki\Rest\RequestInterface;
use MediaWiki\Rest\ResponseException;
use MediaWiki\Rest\ResponseFactory;
use MediaWiki\Rest\Router;
use MediaWiki\Rest\StringStream;
use MediaWiki\Rest\Validator\JsonBodyValidator;
use MediaWiki\Tests\Rest\Handler\HelloHandler;
use MediaWiki\User\UserIdentityValue;
use MediaWikiUnitTestCase;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\NullLogger;
use RuntimeException;
use Throwable;
use UDPTransport;
use Wikimedia\ObjectCache\HashBagOStuff;
use Wikimedia\ParamValidator\ParamValidator;
use Wikimedia\Stats\OutputFormats;
use Wikimedia\Stats\StatsCache;
use Wikimedia\Stats\StatsFactory;
use Wikimedia\TestingAccessWrapper;
/**
* @covers \MediaWiki\Rest\Router
* @covers \MediaWiki\Rest\Handler
*/
class RouterTest extends MediaWikiUnitTestCase {
use RestTestTrait;
private const CANONICAL_SERVER = 'https://wiki.example.com';
private const INTERNAL_SERVER = 'http://api.local:8080';
/** @var Throwable[] */
private $reportedErrors = [];
/** @var HashBagOStuff */
private $cacheBag;
protected function setUp(): void {
parent::setUp();
$this->cacheBag = new HashBagOStuff();
}
private function createRouter(
RequestInterface $request,
?string $authError = null,
array $routeFiles = [ __DIR__ . '/testRoutes.json' ]
): Router {
/** @var MockObject|ErrorReporter $mockErrorReporter */
$mockErrorReporter = $this->createNoOpMock( ErrorReporter::class, [ 'reportError' ] );
$mockErrorReporter->method( 'reportError' )
->willReturnCallback( function ( $e ) {
$this->reportedErrors[] = $e;
} );
$config = [
MainConfigNames::CanonicalServer => self::CANONICAL_SERVER,
MainConfigNames::InternalServer => self::INTERNAL_SERVER,
MainConfigNames::RestPath => '/rest',
MainConfigNames::ScriptPath => '/w'
];
$extraRoutes = [
[ 'path' => '/', 'class' => HelloHandler::class ]
];
return $this->newRouter( [
'routeFiles' => $routeFiles,
'extraRoutes' => $extraRoutes,
'request' => $request,
'config' => $config,
'cacheBag' => $this->cacheBag,
'errorReporter' => $mockErrorReporter,
'basicAuth' => new StaticBasicAuthorizer( $authError ),
] );
}
private function createMockStatsFactory( string $expectedValue ): StatsFactory {
$statsCache = new StatsCache();
$emitter = OutputFormats::getNewEmitter(
'mediawiki',
$statsCache,
OutputFormats::getNewFormatter( OutputFormats::DOGSTATSD )
);
$transport = $this->createMock( UDPTransport::class );
$transport->expects( $this->once() )->method( "emit" )
->with( $this->matchesRegularExpression( $expectedValue ) );
$emitter = $emitter->withTransport( $transport );
return new StatsFactory( $statsCache, $emitter, new NullLogger );
}
public function testEmptyPath() {
// The URI doesn't contain the "/" suffix, so the relative path is empty.
$request = new RequestData( [ 'uri' => new Uri( '/rest' ) ] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 308, $response->getStatusCode() );
$this->assertSame( '/rest/', $response->getHeaderLine( 'location' ) );
}
public function testRootPath() {
// The URI contains only the "/" suffix.
// This should be sufficient to be routed to the prefix-less modules.
// The "/" path is mapped to the HelloHandler in createRouter().
$request = new RequestData( [ 'uri' => new Uri( '/rest/' ) ] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 200, $response->getStatusCode(), (string)$response->getBody() );
}
public function testPrefixMismatch() {
$request = new RequestData( [ 'uri' => new Uri( '/bogus' ) ] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 404, $response->getStatusCode() );
}
public function testWrongMethod() {
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/hello' ),
'method' => 'TRACE'
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 405, $response->getStatusCode() );
$this->assertSame( 'Method Not Allowed', $response->getReasonPhrase() );
$this->assertSame( 'HEAD, GET', $response->getHeaderLine( 'Allow' ) );
}
public function testGetFromUglyPath() {
$request = new RequestData( [
'uri' => new Uri( '/w/rest.php/mock/v1/RouterTest/hello' ),
'method' => 'GET'
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 200, $response->getStatusCode() );
}
public function testHeadToGet() {
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/hello' ),
'method' => 'HEAD'
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 200, $response->getStatusCode() );
}
public function testCorsPreflight() {
$cors = $this->getCorsUtils();
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/hello' ),
'method' => 'OPTIONS'
] );
$router = $this->createRouter( $request );
$router->setCors( $cors );
$response = $router->execute( $request );
$this->assertSame( 204, $response->getStatusCode() );
$this->assertSame(
[ 'HEAD', 'GET', ],
$response->getHeader( 'Access-Control-Allow-Methods' )
);
}
public function testNoMatch() {
$request = new RequestData( [ 'uri' => new Uri( '/rest/bogus' ) ] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 404, $response->getStatusCode() );
// TODO: add more information to the response body and test for its presence here
}
/**
* Constructs a handler that throws an HttpException
*/
public static function throwHandlerFactory(): Handler {
return new class extends Handler {
public function execute() {
throw new HttpException( 'Mock error', 555 );
}
};
}
/**
* Constructs a handler that throws a RuntimeException with a custom code
*/
public static function fatalHandlerFactory(): Handler {
return new class extends Handler {
public function execute() {
throw new RuntimeException( 'Fatal mock error', 12345 );
}
};
}
/**
* Constructs a handler that throws a RedirectException
*/
public static function throwRedirectHandlerFactory(): Handler {
return new class extends Handler {
public function execute() {
throw new RedirectException( 301, 'http://example.com' );
}
};
}
/**
* Constructs a handler that throws a ResponseException with status 200
*/
public static function throwWrappedHandlerFactory(): Handler {
return new class extends Handler {
public function execute() {
$response = $this->getResponseFactory()->create();
$response->setStatus( 200 );
throw new ResponseException( $response );
}
};
}
public function testHttpException() {
$request = new RequestData( [ 'uri' => new Uri( '/rest/mock/v1/RouterTest/throw' ) ] );
$router = $this->createRouter( $request );
$stats = $this->createMockStatsFactory(
"/^mediawiki\.rest_api_errors_total:1\|c\|#path:mock_v1_RouterTest_throw,method:GET,status:555\nmediawiki\.stats_buffered_total:1\|c$/"
);
$router->setStats( $stats );
$response = $router->execute( $request );
$stats->flush();
$this->assertSame( 555, $response->getStatusCode(), (string)$response->getBody() );
$body = $response->getBody();
$body->rewind();
$data = json_decode( $body->getContents(), true );
$this->assertSame( 'Mock error', $data['message'] );
}
public function testFatalException() {
$request = new RequestData( [ 'uri' => new Uri( '/rest/mock/v1/RouterTest/fatal' ) ] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 500, $response->getStatusCode(), (string)$response->getBody() );
$body = $response->getBody();
$body->rewind();
$data = json_decode( $body->getContents(), true );
$this->assertStringContainsString( 'RuntimeException', $data['message'] );
$this->assertNotEmpty( $this->reportedErrors );
$this->assertInstanceOf( RuntimeException::class, $this->reportedErrors[0] );
}
public function testRedirectException() {
$request = new RequestData( [ 'uri' => new Uri( '/rest/mock/v1/RouterTest/throwRedirect' ) ] );
$router = $this->createRouter( $request );
$stats = $this->createMockStatsFactory(
"/^mediawiki\.rest_api_latency_seconds:\d+\.\d+\|ms\|#path:mock_v1_RouterTest_throwRedirect,method:GET,status:301\nmediawiki\.stats_buffered_total:1\|c$/"
);
$router->setStats( $stats );
$response = $router->execute( $request );
$stats->flush();
$this->assertSame( 301, $response->getStatusCode(), (string)$response->getBody() );
$this->assertSame( 'http://example.com', $response->getHeaderLine( 'Location' ) );
}
public function testRedirectDefinition() {
// This route is defined in testRoutes.json without specifying a class or factory.
$request = new RequestData( [ 'uri' => new Uri( '/rest/mock/v1/RouterTest/redirect' ) ] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 308, $response->getStatusCode(), (string)$response->getBody() );
$this->assertSame( '/rest/mock/RouterTest/redirectTarget', $response->getHeaderLine( 'Location' ) );
}
public function testResponseException() {
$request = new RequestData( [ 'uri' => new Uri( '/rest/mock/v1/RouterTest/throwWrapped' ) ] );
$router = $this->createRouter( $request );
$stats = $this->createMockStatsFactory(
"/^mediawiki\.rest_api_latency_seconds:\d+\.\d+\|ms\|#path:mock_v1_RouterTest_throwWrapped,method:GET,status:200\nmediawiki\.stats_buffered_total:1\|c$/"
);
$router->setStats( $stats );
$response = $router->execute( $request );
$stats->flush();
$this->assertSame( 200, $response->getStatusCode(), (string)$response->getBody() );
}
public function testBasicAccess() {
// Using the throwing handler is a way to assert that the handler is not executed
$request = new RequestData( [ 'uri' => new Uri( '/rest/mock/v1/RouterTest/throw' ) ] );
$router = $this->createRouter( $request, 'test-error' );
$response = $router->execute( $request );
$this->assertSame( 403, $response->getStatusCode() );
$body = $response->getBody();
$body->rewind();
$data = json_decode( $body->getContents(), true );
$this->assertSame( 'test-error', $data['error'] );
}
public function testAdditionalEndpoints() {
$request = new RequestData( [
'uri' => new Uri( '/rest/mock-too/RouterTest/hello/two' )
] );
$router = $this->createRouter(
$request,
null,
// NOTE: testAdditionalRoutes uses the old flat format!
[ __DIR__ . '/testRoutes.json', __DIR__ . '/testAdditionalRoutes.json' ]
);
// Routes from flat route files end up on a module that uses the empty prefix.
$this->assertSame( [ 'mock/v1', '' ], $router->getModuleIds() );
$response = $router->execute( $request );
$this->assertSame( 200, $response->getStatusCode() );
}
public function testFlatRouteFile() {
$request = new RequestData( [
'uri' => new Uri( '/rest/ModuleTest/hello/you' )
] );
$router = $this->createRouter(
$request,
null,
[ __DIR__ . '/Module/moduleFlatRoutes.json' ]
);
$this->assertSame( [ '' ], $router->getModuleIds() );
$response = $router->execute( $request );
$this->assertSame( 200, $response->getStatusCode() );
}
public static function providePaths() {
return [
[ '/rest/mock/v1/RouterTest/hello' ],
[ '/rest/mock-too/RouterTest/hello/two' ],
];
}
public static function provideGetRouteUrl() {
yield 'empty' => [ '', '', [], [] ];
yield 'simple route' => [ '/foo/bar', '/foo/bar' ];
yield 'simple route with query' =>
[ '/foo/bar', '/foo/bar?x=1&y=2', [ 'x' => '1', 'y' => '2' ] ];
yield 'simple route with strange query chars' =>
[ '/foo+bar', '/foo+bar?x=%23&y=%25&z=%2B', [ 'x' => '#', 'y' => '%', 'z' => '+' ] ];
yield 'route with simple path params' =>
[ '/foo/{test}/baz', '/foo/bar/baz', [], [ 'test' => 'bar' ] ];
yield 'route with strange path params' =>
[ '/foo/{test}/baz', '/foo/b%25%2F%2Bz/baz', [], [ 'test' => 'b%/+z' ] ];
yield 'space in path does not become a plus' =>
[ '/foo/{test}/baz', '/foo/b%20z/baz', [], [ 'test' => 'b z' ] ];
yield 'route with simple path params and query' =>
[ '/foo/{test}/baz', '/foo/bar/baz?x=1', [ 'x' => '1' ], [ 'test' => 'bar' ] ];
}
/**
* @dataProvider provideGetRouteUrl
*/
public function testGetRoutePath( $route, $expectedUrl, $query = [], $path = [] ) {
$request = new RequestData( [ 'uri' => new Uri( '/rest/mock/v1/route' ) ] );
$router = $this->createRouter( $request );
$path = $router->getRoutePath( $route, $path, $query );
$this->assertStringNotContainsString( self::CANONICAL_SERVER, $path );
$this->assertStringStartsWith( '/', $path );
$expected = new Uri( $expectedUrl );
$actual = new Uri( $path );
$this->assertStringContainsString( $expected->getPath(), $actual->getPath() );
$this->assertStringContainsString( $expected->getQuery(), $actual->getQuery() );
}
/**
* @dataProvider provideGetRouteUrl
*/
public function testGetRouteUrl( $route, $expectedUrl, $query = [], $path = [] ) {
$request = new RequestData( [ 'uri' => new Uri( '/rest/mock/v1/route' ) ] );
$router = $this->createRouter( $request );
$url = $router->getRouteUrl( $route, $path, $query );
$this->assertStringStartsWith( self::CANONICAL_SERVER, $url );
$uri = new Uri( $url );
$this->assertStringContainsString( $expectedUrl, $uri );
}
/**
* @dataProvider provideGetRouteUrl
*/
public function testGetPrivateRouteUrl( $route, $expectedUrl, $query = [], $path = [] ) {
$request = new RequestData( [ 'uri' => new Uri( '/rest/mock/v1/route' ) ] );
$router = $this->createRouter( $request );
$url = $router->getPrivateRouteUrl( $route, $path, $query );
$this->assertStringStartsWith( self::INTERNAL_SERVER, $url );
$uri = new Uri( $url );
$this->assertStringContainsString( $expectedUrl, $uri );
}
public function testCaching() {
$request = new RequestData( [ 'uri' => new Uri( '/rest/mock/v1/route' ) ] );
$router1 = $this->createRouter( $request );
$router1wrapper = TestingAccessWrapper::newFromObject( $router1 );
// Ensure the module map is loaded and cached
$router1->getModule( 'mock' );
// Create a second router
$router2 = $this->createRouter( $request );
$router2wrapper = TestingAccessWrapper::newFromObject( $router2 );
// Destroy $router2's ability to load modules and routes
$router2wrapper->routeFiles = [ '/this/does/not/exist' ];
// Make sure the config hash is set and matches.
$router2wrapper->configHash = $router1wrapper->configHash;
// Check that $router2 can return a module based on cached information.
// Note that this needs both levels of the cache to work.
$module2 = $router2->getModule( 'mock/v1' );
$this->assertNotNull( $module2 );
// Create a third router
$router3 = $this->createRouter( $request );
$router3wrapper = TestingAccessWrapper::newFromObject( $router3 );
// Force a different route file (but don't force the config hash)
$router3wrapper->routeFiles = [ __DIR__ . '/testAdditionalRoutes.json' ];
// This should fail, since the router should detect that the config is
// different, so it can't use cached data.
$module3 = $router3->getModule( 'mock/v1' );
$this->assertNull( $module3 );
}
public function testHandlerDisablesBodyParsing() {
// This is valid JSON, but not an object.
// Automatic parsing will fail, since it re requires
// an array to be returned.
$payload = '"just a test"';
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/stream' ),
'method' => 'PUT',
'bodyContents' => $payload,
'headers' => [ "content-type" => 'application/json' ]
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 200, $response->getStatusCode() );
$responseStream = $response->getBody();
$this->assertSame( $payload, "$responseStream" );
}
/**
* Asserts that handlers can use a custom BodyValidator to add support for
* additional mime types, without overriding parseBodyData(). This ensures
* backwards compatibility with extensions that are not yet aware of
* parseBodyData().
*/
public function testCustomBodyValidator() {
$this->expectDeprecationAndContinue( '/overrides getBodyValidator/' );
$this->expectDeprecationAndContinue( '/Validator::validateBody/' );
$this->expectDeprecationAndContinue( '/JsonBodyValidator/' );
// This is valid JSON, but not an object.
// Automatic parsing will fail, since it re requires
// an array to be returned.
$payload = '{ "test": "yes" }';
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/old-body-validator' ),
'method' => 'PUT',
'bodyContents' => $payload,
'headers' => [ "content-type" => 'application/json-patch+json' ]
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 200, $response->getStatusCode(), (string)$response->getBody() );
}
/**
* Constructs a handler that disables body parsing
*/
public static function streamHandlerFactory(): Handler {
return new class extends Handler {
public function parseBodyData( RequestInterface $request ): ?array {
// Disable parsing
return null;
}
public function execute() {
Assert::assertNull( $this->getRequest()->getParsedBody() );
$body = $this->getRequest()->getBody();
$response = $this->getResponseFactory()->create();
$response->setBody( new StringStream( "$body" ) );
return $response;
}
};
}
/**
* Constructs a handler that uses a BodyValidator object
*/
public static function oldBodyValidatorFactory(): Handler {
return new class extends Handler {
private $postValidationSetupCalled = false;
public function getBodyValidator( $contentType ) {
if ( $contentType !== 'application/json-patch+json' ) {
throw new HttpException(
"Unsupported Content-Type",
415,
);
}
return new JsonBodyValidator( [
'test' => [
ParamValidator::PARAM_REQUIRED => true,
static::PARAM_SOURCE => 'body',
]
] );
}
public function execute() {
$body = $this->getValidatedBody();
Assert::assertIsArray( $body );
Assert::assertArrayHasKey( 'test', $body );
Assert::assertTrue( $this->postValidationSetupCalled );
return "";
}
protected function postValidationSetup() {
$this->postValidationSetupCalled = true;
}
};
}
/**
* Constructs a handler that echos a form data request body
*/
public static function formHandlerFactory(): Handler {
return new class extends Handler {
public function execute() {
return $this->getValidatedBody();
}
public function getParamSettings(): array {
return [
'foo' => [
Handler::PARAM_SOURCE => 'body'
]
];
}
public function getSupportedRequestTypes(): array {
return [
'application/x-www-form-urlencoded',
'multipart/form-data'
];
}
};
}
/**
* Constructs a handler that echos a JSON request body
*/
public static function dataHandlerFactory(): Handler {
return new class extends Handler {
public function execute() {
return $this->getValidatedBody();
}
public function getParamSettings(): array {
return [
'foo' => [
Handler::PARAM_SOURCE => 'body'
]
];
}
};
}
public function testGetRequestFailsWithBody() {
$this->markTestSkipped( 'T359509' );
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
'method' => 'GET',
'bodyContents' => '{"foo":"bar"}',
'headers' => [ "content-type" => 'application/json' ]
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 400, $response->getStatusCode() );
}
public function testGetRequestIgnoresEmptyBody() {
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
'method' => 'GET',
'bodyContents' => '',
'headers' => [
"content-length" => 0,
"content-type" => 'text/plain'
]
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 200, $response->getStatusCode() );
}
public function testPostRequestFailsWithoutBody() {
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
'method' => 'POST',
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 411, $response->getStatusCode() );
}
public function testEmptyBodyWithoutContentTypePasses() {
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
'method' => 'POST',
'headers' => [ 'content-length' => '0' ],
'bodyContent' => '',
// Should pass even without content-type!
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 200, $response->getStatusCode() );
}
public function testRequestBodyWithoutContentTypeFails() {
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
'method' => 'POST',
'bodyContents' => '{"foo":"bar"}', // Request body without content-type
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 415, $response->getStatusCode() );
}
public function testDeleteRequestWithoutBody() {
// Test DELETE request without body
$requestWithoutBody = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
'method' => 'DELETE',
] );
$router = $this->createRouter( $requestWithoutBody );
$responseWithoutBody = $router->execute( $requestWithoutBody );
$this->assertSame( 200, $responseWithoutBody->getStatusCode() );
}
public function testDeleteRequestWithBody() {
// Test DELETE request with body
$requestWithBody = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
'method' => 'DELETE',
'bodyContents' => '{"bodyParam":"bar"}',
'headers' => [ "content-type" => 'application/json' ]
] );
$router = $this->createRouter( $requestWithBody );
$responseWithBody = $router->execute( $requestWithBody );
$this->assertSame( 200, $responseWithBody->getStatusCode() );
}
public function testUnsupportedContentTypeReturns415() {
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
'method' => 'POST',
'bodyContents' => '{"foo":"bar"}',
'headers' => [ "content-type" => 'text/plain' ] // Unsupported content type
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 415, $response->getStatusCode() );
}
public function testFormDataReturns415() {
$request = new RequestData( [
// NOTE: The data handler will fail with form data,
// only json is supported per default.
'uri' => new Uri( '/rest/mock/v1/RouterTest/data-handler' ),
'method' => 'POST',
'postParams' => [ 'foo' => 'bar' ],
'headers' => [ "content-type" => 'application/x-www-form-urlencoded' ]
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 415, $response->getStatusCode() );
}
public function testFormDataSupported() {
// See T362850
$this->expectDeprecationAndContinue( '/The "post" source is deprecated/' );
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/echo_form_data' ),
'method' => 'POST',
'postParams' => [ 'foo' => 'bar' ],
'headers' => [ "content-type" => 'application/x-www-form-urlencoded' ]
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 200, $response->getStatusCode() );
// Check if the response contains a field called 'parsedBody'
$body = $response->getBody();
$body->rewind();
$data = json_decode( $body->getContents(), true );
$this->assertSame( [ 'foo' => 'bar' ], $data[ 'parsedBody' ] );
}
public function testJsonBody() {
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
'method' => 'POST',
'bodyContents' => '{"bodyParam":"bar"}',
'headers' => [ "content-type" => 'application/json' ]
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 200, $response->getStatusCode() );
$body = $response->getBody();
$body->rewind();
$data = json_decode( $body->getContents(), true );
// Check the value of 'parsedBody' and 'validateBody' fields
$this->assertEquals( [ 'bodyParam' => 'bar' ], $data['parsedBody'] );
$this->assertEquals( [ 'bodyParam' => 'bar' ], $data['validatedBody'] );
$this->assertArrayNotHasKey( 'bodyParam', $data['validatedParams'] );
}
public function testFormDataBody() {
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/echo' ),
'method' => 'POST',
'postParams' => [ 'bodyParam' => 'bar' ],
'headers' => [
"content-type" => 'application/x-www-form-urlencoded',
"content-length" => 123,
]
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 200, $response->getStatusCode(), (string)$response->getBody() );
$body = $response->getBody();
$body->rewind();
$data = json_decode( $body->getContents(), true );
// The body parameter should be in parsedBody and validatedBody,
// but not in validatedParams.
$this->assertEquals( [ 'bodyParam' => 'bar' ], $data['parsedBody'] );
$this->assertEquals( [ 'bodyParam' => 'bar' ], $data['validatedBody'] );
$this->assertArrayNotHasKey( 'bodyParam', $data['validatedParams'] );
}
public function testFormDataBody_post() {
// See T362850
$this->expectDeprecationAndContinue( '/The "post" source is deprecated/' );
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/echo_form_data' ),
'method' => 'POST',
'postParams' => [ 'postParam' => 'bar' ],
'headers' => [
"content-type" => 'application/x-www-form-urlencoded',
"content-length" => 123,
]
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 200, $response->getStatusCode(), (string)$response->getBody() );
$body = $response->getBody();
$body->rewind();
$data = json_decode( $body->getContents(), true );
// The post parameter should be in parsedBody and validatedParams,
// but not as in validatedBody.
$this->assertEquals( [ 'postParam' => 'bar' ], $data['parsedBody'] );
$this->assertArrayHasKey( 'postParam', $data['validatedParams'] );
$this->assertArrayNotHasKey( 'postParam', $data['validatedBody'] );
}
public function testHandlerCanAccessValidatedParams() {
$request = new RequestData( [
'uri' => new Uri( '/rest/mock/v1/RouterTest/echo/bar' ),
'method' => 'POST',
'headers' => [ "content-type" => 'application/json' ],
'bodyContents' => '{}'
] );
$router = $this->createRouter( $request );
$response = $router->execute( $request );
$this->assertSame( 200, $response->getStatusCode(), (string)$response->getBody() );
// Check if the response contains a field called 'pathParams'
$body = $response->getBody();
$body->rewind();
$data = json_decode( $body->getContents(), true );
$this->assertArrayHasKey( 'validatedParams', $data );
// Check the value of the 'pathParams' field
$validatedParams = $data['validatedParams'];
$this->assertEquals( 'bar', $validatedParams[ 'pathParam' ], (string)$response->getBody() );
}
/**
* @return CorsUtils
*/
private function getCorsUtils(): CorsUtils {
$cors = new CorsUtils(
new ServiceOptions(
CorsUtils::CONSTRUCTOR_OPTIONS,
[
MainConfigNames::AllowedCorsHeaders => [],
MainConfigNames::AllowCrossOrigin => [],
MainConfigNames::RestAllowCrossOriginCookieAuth => [],
MainConfigNames::CanonicalServer => 'testing',
MainConfigNames::CrossSiteAJAXdomains => [],
MainConfigNames::CrossSiteAJAXdomainExceptions => [],
]
),
new ResponseFactory( [] ),
new UserIdentityValue(
1,
'Test'
)
);
return $cors;
}
}
|