ServerTest.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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\Server;
  24. use Cake\Http\ServerRequest;
  25. use Cake\Http\Session;
  26. use Cake\TestSuite\TestCase;
  27. use InvalidArgumentException;
  28. use Laminas\Diactoros\Response as LaminasResponse;
  29. use Laminas\Diactoros\ServerRequest as LaminasServerRequest;
  30. use Psr\Http\Message\ResponseInterface;
  31. use TestApp\Http\MiddlewareApplication;
  32. require_once __DIR__ . '/server_mocks.php';
  33. /**
  34. * Server test case
  35. */
  36. class ServerTest extends TestCase
  37. {
  38. /**
  39. * @var string
  40. */
  41. protected $config;
  42. /**
  43. * @var array
  44. */
  45. protected $server;
  46. /**
  47. * @var \Cake\Http\MiddlewareQueue
  48. */
  49. protected $middlewareQueue;
  50. /**
  51. * Setup
  52. */
  53. public function setUp(): void
  54. {
  55. parent::setUp();
  56. $this->server = $_SERVER;
  57. $this->config = dirname(dirname(__DIR__)) . '/test_app/config';
  58. $GLOBALS['mockedHeaders'] = [];
  59. $GLOBALS['mockedHeadersSent'] = true;
  60. }
  61. /**
  62. * Teardown
  63. */
  64. public function tearDown(): void
  65. {
  66. parent::tearDown();
  67. $_SERVER = $this->server;
  68. unset($GLOBALS['mockedHeadersSent']);
  69. }
  70. /**
  71. * test get/set on the app
  72. */
  73. public function testAppGetSet(): void
  74. {
  75. /** @var \Cake\Http\BaseApplication|\PHPUnit\Framework\MockObject\MockObject $app */
  76. $app = $this->getMockBuilder(BaseApplication::class)
  77. ->setConstructorArgs([$this->config])
  78. ->getMock();
  79. $manager = new EventManager();
  80. $app->method('getEventManager')
  81. ->willReturn($manager);
  82. $server = new Server($app);
  83. $this->assertSame($app, $server->getApp());
  84. $this->assertSame($app->getEventManager(), $server->getEventManager());
  85. }
  86. /**
  87. * test run building a response
  88. */
  89. public function testRunWithRequest(): void
  90. {
  91. $request = new ServerRequest();
  92. $request = $request->withHeader('X-pass', 'request header');
  93. $app = new MiddlewareApplication($this->config);
  94. $server = new Server($app);
  95. $res = $server->run($request);
  96. $this->assertSame(
  97. 'source header',
  98. $res->getHeaderLine('X-testing'),
  99. 'Input response is carried through out middleware'
  100. );
  101. $this->assertSame(
  102. 'request header',
  103. $res->getHeaderLine('X-pass'),
  104. 'Request is used in middleware'
  105. );
  106. }
  107. /**
  108. * test run calling plugin hooks
  109. */
  110. public function testRunCallingPluginHooks(): void
  111. {
  112. $request = new ServerRequest();
  113. $request = $request->withHeader('X-pass', 'request header');
  114. /** @var \TestApp\Http\MiddlewareApplication|\PHPUnit\Framework\MockObject\MockObject $app */
  115. $app = $this->getMockBuilder(MiddlewareApplication::class)
  116. ->onlyMethods(['pluginBootstrap', 'pluginMiddleware'])
  117. ->addMethods(['pluginEvents'])
  118. ->setConstructorArgs([$this->config])
  119. ->getMock();
  120. $app->expects($this->once())
  121. ->method('pluginBootstrap');
  122. $app->expects($this->once())
  123. ->method('pluginMiddleware')
  124. ->with($this->isInstanceOf(MiddlewareQueue::class))
  125. ->will($this->returnCallback(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('Laminas\HttpHandlerRunner\Emitter\EmitterInterface')->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. /** @var \Cake\Http\BaseApplication|\PHPUnit\Framework\MockObject\MockObject $app */
  272. $app = $this->getMockForAbstractClass(
  273. BaseApplication::class,
  274. [$this->config]
  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. }