ServerTest.php 11 KB

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