ServerTest.php 10 KB

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