ServerTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.3.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Http;
  17. use Cake\Core\HttpApplicationInterface;
  18. use Cake\Event\EventInterface;
  19. use Cake\Event\EventManager;
  20. use Cake\Http\BaseApplication;
  21. use Cake\Http\CallbackStream;
  22. use Cake\Http\MiddlewareQueue;
  23. use Cake\Http\Response;
  24. use Cake\Http\ResponseEmitter;
  25. use Cake\Http\Server;
  26. use Cake\Http\ServerRequest;
  27. use Cake\Http\Session;
  28. use Cake\TestSuite\TestCase;
  29. use InvalidArgumentException;
  30. use Laminas\Diactoros\Response as LaminasResponse;
  31. use Laminas\Diactoros\ServerRequest as LaminasServerRequest;
  32. use Mockery;
  33. use Psr\Http\Message\ResponseInterface;
  34. use Psr\Http\Message\ServerRequestInterface;
  35. use TestApp\Http\MiddlewareApplication;
  36. require_once __DIR__ . '/server_mocks.php';
  37. /**
  38. * Server test case
  39. */
  40. class ServerTest extends TestCase
  41. {
  42. /**
  43. * @var string
  44. */
  45. protected $config;
  46. /**
  47. * @var array
  48. */
  49. protected $server;
  50. /**
  51. * @var \Cake\Http\MiddlewareQueue
  52. */
  53. protected $middlewareQueue;
  54. /**
  55. * Setup
  56. */
  57. public function setUp(): void
  58. {
  59. parent::setUp();
  60. $this->server = $_SERVER;
  61. $this->config = dirname(__DIR__, 2) . '/test_app/config';
  62. $GLOBALS['mockedHeaders'] = [];
  63. $GLOBALS['mockedHeadersSent'] = true;
  64. }
  65. /**
  66. * Teardown
  67. */
  68. public function tearDown(): void
  69. {
  70. parent::tearDown();
  71. $_SERVER = $this->server;
  72. unset($GLOBALS['mockedHeadersSent']);
  73. }
  74. /**
  75. * test get/set on the app
  76. */
  77. public function testAppGetSet(): void
  78. {
  79. $eventManager = new EventManager();
  80. $app = new class ($this->config, $eventManager) extends BaseApplication
  81. {
  82. public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
  83. {
  84. return $middlewareQueue;
  85. }
  86. };
  87. $server = new Server($app);
  88. $this->assertSame($app, $server->getApp());
  89. $this->assertSame($app->getEventManager(), $server->getEventManager());
  90. }
  91. /**
  92. * test run building a response
  93. */
  94. public function testRunWithRequest(): void
  95. {
  96. $request = new ServerRequest();
  97. $request = $request->withHeader('X-pass', 'request header');
  98. $app = new MiddlewareApplication($this->config);
  99. $server = new Server($app);
  100. $res = $server->run($request);
  101. $this->assertSame(
  102. 'source header',
  103. $res->getHeaderLine('X-testing'),
  104. 'Input response is carried through out middleware'
  105. );
  106. $this->assertSame(
  107. 'request header',
  108. $res->getHeaderLine('X-pass'),
  109. 'Request is used in middleware'
  110. );
  111. }
  112. /**
  113. * test run calling plugin hooks
  114. */
  115. public function testRunCallingPluginHooks(): void
  116. {
  117. $request = new ServerRequest();
  118. $request = $request->withHeader('X-pass', 'request header');
  119. /** @var \TestApp\Http\MiddlewareApplication|\Mockery\MockInterface $app */
  120. $app = Mockery::mock(MiddlewareApplication::class, [$this->config])
  121. ->shouldAllowMockingMethod('pluginEvents')
  122. ->makePartial();
  123. $app->shouldReceive('pluginBootstrap', 'pluginMiddleware')
  124. ->with(Mockery::type(MiddlewareQueue::class))
  125. ->andReturnUsing(function ($middleware) {
  126. return $middleware;
  127. });
  128. $server = new Server($app);
  129. $res = $server->run($request);
  130. $this->assertSame(
  131. 'source header',
  132. $res->getHeaderLine('X-testing'),
  133. 'Input response is carried through out middleware'
  134. );
  135. $this->assertSame(
  136. 'request header',
  137. $res->getHeaderLine('X-pass'),
  138. 'Request is used in middleware'
  139. );
  140. }
  141. /**
  142. * test run building a request from globals.
  143. */
  144. public function testRunWithGlobals(): void
  145. {
  146. $_SERVER['HTTP_X_PASS'] = 'globalvalue';
  147. $app = new MiddlewareApplication($this->config);
  148. $server = new Server($app);
  149. $res = $server->run();
  150. $this->assertSame(
  151. 'globalvalue',
  152. $res->getHeaderLine('X-pass'),
  153. 'Default request is made from server'
  154. );
  155. }
  156. /**
  157. * Test middleware being invoked.
  158. */
  159. public function testRunMultipleMiddlewareSuccess(): void
  160. {
  161. $app = new MiddlewareApplication($this->config);
  162. $server = new Server($app);
  163. $res = $server->run();
  164. $this->assertSame('first', $res->getHeaderLine('X-First'));
  165. $this->assertSame('second', $res->getHeaderLine('X-Second'));
  166. }
  167. /**
  168. * Test that run closes session after invoking the application (if CakePHP ServerRequest is used).
  169. */
  170. public function testRunClosesSessionIfServerRequestUsed(): void
  171. {
  172. $sessionMock = $this->createMock(Session::class);
  173. $sessionMock->expects($this->once())
  174. ->method('close');
  175. $app = new MiddlewareApplication($this->config);
  176. $server = new Server($app);
  177. $request = new ServerRequest(['session' => $sessionMock]);
  178. $res = $server->run($request);
  179. // assert that app was executed correctly
  180. $this->assertSame(
  181. 200,
  182. $res->getStatusCode(),
  183. 'Application was expected to be executed'
  184. );
  185. $this->assertSame(
  186. 'source header',
  187. $res->getHeaderLine('X-testing'),
  188. 'Application was expected to be executed'
  189. );
  190. }
  191. /**
  192. * Test that run does not close the session if CakePHP ServerRequest is not used.
  193. */
  194. public function testRunDoesNotCloseSessionIfServerRequestNotUsed(): void
  195. {
  196. $request = new LaminasServerRequest();
  197. $app = new MiddlewareApplication($this->config);
  198. $server = new Server($app);
  199. $res = $server->run($request);
  200. // assert that app was executed correctly
  201. $this->assertSame(
  202. 200,
  203. $res->getStatusCode(),
  204. 'Application was expected to be executed'
  205. );
  206. $this->assertSame(
  207. 'source header',
  208. $res->getHeaderLine('X-testing'),
  209. 'Application was expected to be executed'
  210. );
  211. }
  212. /**
  213. * Test that emit invokes the appropriate methods on the emitter.
  214. */
  215. public function testEmit(): void
  216. {
  217. $app = new MiddlewareApplication($this->config);
  218. $server = new Server($app);
  219. $response = $server->run();
  220. $final = $response
  221. ->withHeader('X-First', 'first')
  222. ->withHeader('X-Second', 'second');
  223. $emitter = $this->getMockBuilder(ResponseEmitter::class)->getMock();
  224. $emitter->expects($this->once())
  225. ->method('emit')
  226. ->with($final);
  227. $server->emit($final, $emitter);
  228. }
  229. /**
  230. * Test that emit invokes the appropriate methods on the emitter.
  231. */
  232. public function testEmitCallbackStream(): void
  233. {
  234. $GLOBALS['mockedHeadersSent'] = false;
  235. $response = new LaminasResponse('php://memory', 200, ['x-testing' => 'source header']);
  236. $response = $response->withBody(new CallbackStream(function (): void {
  237. echo 'body content';
  238. }));
  239. $app = new MiddlewareApplication($this->config);
  240. $server = new Server($app);
  241. ob_start();
  242. $server->emit($response);
  243. $result = ob_get_clean();
  244. $this->assertSame('body content', $result);
  245. }
  246. /**
  247. * Ensure that the Server.buildMiddleware event is fired.
  248. */
  249. public function testBuildMiddlewareEvent(): void
  250. {
  251. $app = new MiddlewareApplication($this->config);
  252. $server = new Server($app);
  253. $called = false;
  254. $server->getEventManager()->on('Server.buildMiddleware', function (EventInterface $event, MiddlewareQueue $middlewareQueue) use (&$called): void {
  255. $middlewareQueue->add(function ($request, $handler) use (&$called) {
  256. $called = true;
  257. return $handler->handle($request);
  258. });
  259. $this->middlewareQueue = $middlewareQueue;
  260. });
  261. $server->run();
  262. $this->assertTrue($called, 'Middleware added in the event was not triggered.');
  263. $this->middlewareQueue->seek(3);
  264. $this->assertInstanceOf('Closure', $this->middlewareQueue->current()->getCallable(), '2nd last middleware is a closure');
  265. }
  266. /**
  267. * test event manager proxies to the application.
  268. */
  269. public function testEventManagerProxies(): void
  270. {
  271. $app = new class ($this->config) extends BaseApplication
  272. {
  273. public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
  274. {
  275. return $middlewareQueue;
  276. }
  277. };
  278. $server = new Server($app);
  279. $this->assertSame($app->getEventManager(), $server->getEventManager());
  280. }
  281. /**
  282. * test event manager cannot be set on applications without events.
  283. */
  284. public function testGetEventManagerNonEventedApplication(): void
  285. {
  286. $app = new class implements HttpApplicationInterface {
  287. public function bootstrap(): void
  288. {
  289. }
  290. public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
  291. {
  292. return $middlewareQueue;
  293. }
  294. public function handle(ServerRequestInterface $request): ResponseInterface
  295. {
  296. return new Response();
  297. }
  298. };
  299. $server = new Server($app);
  300. $this->assertSame(EventManager::instance(), $server->getEventManager());
  301. }
  302. /**
  303. * test event manager cannot be set on applications without events.
  304. */
  305. public function testSetEventManagerNonEventedApplication(): void
  306. {
  307. $app = new class implements HttpApplicationInterface {
  308. public function bootstrap(): void
  309. {
  310. }
  311. public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
  312. {
  313. return $middlewareQueue;
  314. }
  315. public function handle(ServerRequestInterface $request): ResponseInterface
  316. {
  317. return new Response();
  318. }
  319. };
  320. $events = new EventManager();
  321. $server = new Server($app);
  322. $this->expectException(InvalidArgumentException::class);
  323. $server->setEventManager($events);
  324. }
  325. /**
  326. * Test server run works without an application implementing ContainerApplicationInterface
  327. */
  328. public function testAppWithoutContainerApplicationInterface(): void
  329. {
  330. $app = new class implements HttpApplicationInterface {
  331. public function bootstrap(): void
  332. {
  333. }
  334. public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
  335. {
  336. return $middlewareQueue;
  337. }
  338. public function handle(ServerRequestInterface $request): ResponseInterface
  339. {
  340. return new Response();
  341. }
  342. };
  343. $server = new Server($app);
  344. $request = new ServerRequest();
  345. $this->assertInstanceOf(ResponseInterface::class, $server->run($request));
  346. }
  347. public function testTerminateEvent(): void
  348. {
  349. $request = new ServerRequest();
  350. $app = new MiddlewareApplication($this->config);
  351. $app->getContainer()->add(ServerRequest::class, $request);
  352. $server = new Server($app);
  353. $triggered = false;
  354. $server->getEventManager()->on(
  355. 'Server.terminate',
  356. function ($event, $request, $response) use (&$triggered): void {
  357. $triggered = true;
  358. $this->assertInstanceOf(ServerRequest::class, $request);
  359. $this->assertInstanceOf(Response::class, $response);
  360. }
  361. );
  362. $emitter = new class extends ResponseEmitter {
  363. public function emit(ResponseInterface $response, $stream = null): bool
  364. {
  365. return true;
  366. }
  367. };
  368. $server->emit(new Response(), $emitter);
  369. $this->assertTrue($triggered);
  370. }
  371. }