ServerTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 TestApp\Http\MiddlewareApplication;
  35. require_once __DIR__ . '/server_mocks.php';
  36. /**
  37. * Server test case
  38. */
  39. class ServerTest extends TestCase
  40. {
  41. /**
  42. * @var string
  43. */
  44. protected $config;
  45. /**
  46. * @var array
  47. */
  48. protected $server;
  49. /**
  50. * @var \Cake\Http\MiddlewareQueue
  51. */
  52. protected $middlewareQueue;
  53. /**
  54. * Setup
  55. */
  56. public function setUp(): void
  57. {
  58. parent::setUp();
  59. $this->server = $_SERVER;
  60. $this->config = dirname(__DIR__, 2) . '/test_app/config';
  61. $GLOBALS['mockedHeaders'] = [];
  62. $GLOBALS['mockedHeadersSent'] = true;
  63. }
  64. /**
  65. * Teardown
  66. */
  67. public function tearDown(): void
  68. {
  69. parent::tearDown();
  70. $_SERVER = $this->server;
  71. unset($GLOBALS['mockedHeadersSent']);
  72. }
  73. /**
  74. * test get/set on the app
  75. */
  76. public function testAppGetSet(): void
  77. {
  78. /** @var \Cake\Http\BaseApplication|\PHPUnit\Framework\MockObject\MockObject $app */
  79. $app = $this->getMockBuilder(BaseApplication::class)
  80. ->setConstructorArgs([$this->config])
  81. ->getMock();
  82. $manager = new EventManager();
  83. $app->method('getEventManager')
  84. ->willReturn($manager);
  85. $server = new Server($app);
  86. $this->assertSame($app, $server->getApp());
  87. $this->assertSame($app->getEventManager(), $server->getEventManager());
  88. }
  89. /**
  90. * test run building a response
  91. */
  92. public function testRunWithRequest(): void
  93. {
  94. $request = new ServerRequest();
  95. $request = $request->withHeader('X-pass', 'request header');
  96. $app = new MiddlewareApplication($this->config);
  97. $server = new Server($app);
  98. $res = $server->run($request);
  99. $this->assertSame(
  100. 'source header',
  101. $res->getHeaderLine('X-testing'),
  102. 'Input response is carried through out middleware'
  103. );
  104. $this->assertSame(
  105. 'request header',
  106. $res->getHeaderLine('X-pass'),
  107. 'Request is used in middleware'
  108. );
  109. }
  110. /**
  111. * test run calling plugin hooks
  112. */
  113. public function testRunCallingPluginHooks(): void
  114. {
  115. $request = new ServerRequest();
  116. $request = $request->withHeader('X-pass', 'request header');
  117. /** @var \TestApp\Http\MiddlewareApplication|\Mockery\MockInterface $app */
  118. $app = Mockery::mock(MiddlewareApplication::class, [$this->config])
  119. ->shouldAllowMockingMethod('pluginEvents')
  120. ->makePartial();
  121. $app->shouldReceive('pluginBootstrap', 'pluginMiddleware')
  122. ->with(Mockery::type(MiddlewareQueue::class))
  123. ->andReturnUsing(function ($middleware) {
  124. return $middleware;
  125. });
  126. $server = new Server($app);
  127. $res = $server->run($request);
  128. $this->assertSame(
  129. 'source header',
  130. $res->getHeaderLine('X-testing'),
  131. 'Input response is carried through out middleware'
  132. );
  133. $this->assertSame(
  134. 'request header',
  135. $res->getHeaderLine('X-pass'),
  136. 'Request is used in middleware'
  137. );
  138. }
  139. /**
  140. * test run building a request from globals.
  141. */
  142. public function testRunWithGlobals(): void
  143. {
  144. $_SERVER['HTTP_X_PASS'] = 'globalvalue';
  145. $app = new MiddlewareApplication($this->config);
  146. $server = new Server($app);
  147. $res = $server->run();
  148. $this->assertSame(
  149. 'globalvalue',
  150. $res->getHeaderLine('X-pass'),
  151. 'Default request is made from server'
  152. );
  153. }
  154. /**
  155. * Test middleware being invoked.
  156. */
  157. public function testRunMultipleMiddlewareSuccess(): void
  158. {
  159. $app = new MiddlewareApplication($this->config);
  160. $server = new Server($app);
  161. $res = $server->run();
  162. $this->assertSame('first', $res->getHeaderLine('X-First'));
  163. $this->assertSame('second', $res->getHeaderLine('X-Second'));
  164. }
  165. /**
  166. * Test that run closes session after invoking the application (if CakePHP ServerRequest is used).
  167. */
  168. public function testRunClosesSessionIfServerRequestUsed(): void
  169. {
  170. $sessionMock = $this->createMock(Session::class);
  171. $sessionMock->expects($this->once())
  172. ->method('close');
  173. $app = new MiddlewareApplication($this->config);
  174. $server = new Server($app);
  175. $request = new ServerRequest(['session' => $sessionMock]);
  176. $res = $server->run($request);
  177. // assert that app was executed correctly
  178. $this->assertSame(
  179. 200,
  180. $res->getStatusCode(),
  181. 'Application was expected to be executed'
  182. );
  183. $this->assertSame(
  184. 'source header',
  185. $res->getHeaderLine('X-testing'),
  186. 'Application was expected to be executed'
  187. );
  188. }
  189. /**
  190. * Test that run does not close the session if CakePHP ServerRequest is not used.
  191. */
  192. public function testRunDoesNotCloseSessionIfServerRequestNotUsed(): void
  193. {
  194. $request = new LaminasServerRequest();
  195. $app = new MiddlewareApplication($this->config);
  196. $server = new Server($app);
  197. $res = $server->run($request);
  198. // assert that app was executed correctly
  199. $this->assertSame(
  200. 200,
  201. $res->getStatusCode(),
  202. 'Application was expected to be executed'
  203. );
  204. $this->assertSame(
  205. 'source header',
  206. $res->getHeaderLine('X-testing'),
  207. 'Application was expected to be executed'
  208. );
  209. }
  210. /**
  211. * Test that emit invokes the appropriate methods on the emitter.
  212. */
  213. public function testEmit(): void
  214. {
  215. $app = new MiddlewareApplication($this->config);
  216. $server = new Server($app);
  217. $response = $server->run();
  218. $final = $response
  219. ->withHeader('X-First', 'first')
  220. ->withHeader('X-Second', 'second');
  221. $emitter = $this->getMockBuilder(ResponseEmitter::class)->getMock();
  222. $emitter->expects($this->once())
  223. ->method('emit')
  224. ->with($final);
  225. $server->emit($final, $emitter);
  226. }
  227. /**
  228. * Test that emit invokes the appropriate methods on the emitter.
  229. */
  230. public function testEmitCallbackStream(): void
  231. {
  232. $GLOBALS['mockedHeadersSent'] = false;
  233. $response = new LaminasResponse('php://memory', 200, ['x-testing' => 'source header']);
  234. $response = $response->withBody(new CallbackStream(function (): void {
  235. echo 'body content';
  236. }));
  237. $app = new MiddlewareApplication($this->config);
  238. $server = new Server($app);
  239. ob_start();
  240. $server->emit($response);
  241. $result = ob_get_clean();
  242. $this->assertSame('body content', $result);
  243. }
  244. /**
  245. * Ensure that the Server.buildMiddleware event is fired.
  246. */
  247. public function testBuildMiddlewareEvent(): void
  248. {
  249. $app = new MiddlewareApplication($this->config);
  250. $server = new Server($app);
  251. $called = false;
  252. $server->getEventManager()->on('Server.buildMiddleware', function (EventInterface $event, MiddlewareQueue $middlewareQueue) use (&$called): void {
  253. $middlewareQueue->add(function ($request, $handler) use (&$called) {
  254. $called = true;
  255. return $handler->handle($request);
  256. });
  257. $this->middlewareQueue = $middlewareQueue;
  258. });
  259. $server->run();
  260. $this->assertTrue($called, 'Middleware added in the event was not triggered.');
  261. $this->middlewareQueue->seek(3);
  262. $this->assertInstanceOf('Closure', $this->middlewareQueue->current()->getCallable(), '2nd last middleware is a closure');
  263. }
  264. /**
  265. * test event manager proxies to the application.
  266. */
  267. public function testEventManagerProxies(): void
  268. {
  269. $app = new class ($this->config) extends BaseApplication
  270. {
  271. public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
  272. {
  273. return $middlewareQueue;
  274. }
  275. };
  276. $server = new Server($app);
  277. $this->assertSame($app->getEventManager(), $server->getEventManager());
  278. }
  279. /**
  280. * test event manager cannot be set on applications without events.
  281. */
  282. public function testGetEventManagerNonEventedApplication(): void
  283. {
  284. /** @var \Cake\Core\HttpApplicationInterface|\PHPUnit\Framework\MockObject\MockObject $app */
  285. $app = $this->createMock(HttpApplicationInterface::class);
  286. $server = new Server($app);
  287. $this->assertSame(EventManager::instance(), $server->getEventManager());
  288. }
  289. /**
  290. * test event manager cannot be set on applications without events.
  291. */
  292. public function testSetEventManagerNonEventedApplication(): void
  293. {
  294. /** @var \Cake\Core\HttpApplicationInterface|\PHPUnit\Framework\MockObject\MockObject $app */
  295. $app = $this->createMock(HttpApplicationInterface::class);
  296. $events = new EventManager();
  297. $server = new Server($app);
  298. $this->expectException(InvalidArgumentException::class);
  299. $server->setEventManager($events);
  300. }
  301. /**
  302. * Test server run works without an application implementing ContainerApplicationInterface
  303. */
  304. public function testAppWithoutContainerApplicationInterface(): void
  305. {
  306. /** @var \Cake\Core\HttpApplicationInterface|\PHPUnit\Framework\MockObject\MockObject $app */
  307. $app = $this->createMock(HttpApplicationInterface::class);
  308. $server = new Server($app);
  309. $request = new ServerRequest();
  310. $this->assertInstanceOf(ResponseInterface::class, $server->run($request));
  311. }
  312. public function testTerminateEvent(): void
  313. {
  314. $request = new ServerRequest();
  315. $app = new MiddlewareApplication($this->config);
  316. $app->getContainer()->add(ServerRequest::class, $request);
  317. $server = new Server($app);
  318. $triggered = false;
  319. $server->getEventManager()->on(
  320. 'Server.terminate',
  321. function ($event, $request, $response) use (&$triggered) {
  322. $triggered = true;
  323. $this->assertInstanceOf(ServerRequest::class, $request);
  324. $this->assertInstanceOf(Response::class, $response);
  325. }
  326. );
  327. $emitter = $this->getMockBuilder(ResponseEmitter::class)->getMock();
  328. $emitter->expects($this->once())
  329. ->method('emit')
  330. ->willReturn(true);
  331. $server->emit(new Response(), $emitter);
  332. $this->assertTrue($triggered);
  333. }
  334. }