ServerTest.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.3.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase;
  16. use Cake\Core\HttpApplicationInterface;
  17. use Cake\Event\Event;
  18. use Cake\Event\EventList;
  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\TestSuite\TestCase;
  25. use InvalidArgumentException;
  26. use Psr\Http\Message\ResponseInterface;
  27. use RuntimeException;
  28. use TestApp\Http\BadResponseApplication;
  29. use TestApp\Http\EventApplication;
  30. use TestApp\Http\InvalidMiddlewareApplication;
  31. use TestApp\Http\MiddlewareApplication;
  32. use Zend\Diactoros\Response;
  33. use Zend\Diactoros\ServerRequestFactory;
  34. require_once __DIR__ . '/server_mocks.php';
  35. /**
  36. * Server test case
  37. */
  38. class ServerTest extends TestCase
  39. {
  40. /**
  41. * Setup
  42. *
  43. * @return void
  44. */
  45. public function setUp()
  46. {
  47. parent::setUp();
  48. $this->server = $_SERVER;
  49. $this->config = dirname(dirname(__DIR__));
  50. $GLOBALS['mockedHeaders'] = [];
  51. $GLOBALS['mockedHeadersSent'] = true;
  52. }
  53. /**
  54. * Teardown
  55. *
  56. * @return void
  57. */
  58. public function tearDown()
  59. {
  60. parent::tearDown();
  61. $_SERVER = $this->server;
  62. unset($GLOBALS['mockedHeadersSent']);
  63. }
  64. /**
  65. * test get/set on the app
  66. *
  67. * @return void
  68. */
  69. public function testAppGetSet()
  70. {
  71. $app = $this->getMockBuilder('Cake\Http\BaseApplication')
  72. ->setConstructorArgs([$this->config])
  73. ->getMock();
  74. $manager = new EventManager();
  75. $app->method('getEventManager')
  76. ->willReturn($manager);
  77. $server = new Server($app);
  78. $this->assertSame($app, $server->getApp($app));
  79. $this->assertSame($app->getEventManager(), $server->getEventManager());
  80. }
  81. /**
  82. * test run building a response
  83. *
  84. * @return void
  85. */
  86. public function testRunWithRequestAndResponse()
  87. {
  88. $response = new Response('php://memory', 200, ['X-testing' => 'source header']);
  89. $request = ServerRequestFactory::fromGlobals();
  90. $request = $request->withHeader('X-pass', 'request header');
  91. $app = new MiddlewareApplication($this->config);
  92. $server = new Server($app);
  93. $res = $server->run($request, $response);
  94. $this->assertEquals(
  95. 'source header',
  96. $res->getHeaderLine('X-testing'),
  97. 'Input response is carried through out middleware'
  98. );
  99. $this->assertEquals(
  100. 'request header',
  101. $res->getHeaderLine('X-pass'),
  102. 'Request is used in middleware'
  103. );
  104. }
  105. /**
  106. * test run calling plugin hooks
  107. *
  108. * @return void
  109. */
  110. public function testRunCallingPluginHooks()
  111. {
  112. $response = new Response('php://memory', 200, ['X-testing' => 'source header']);
  113. $request = ServerRequestFactory::fromGlobals();
  114. $request = $request->withHeader('X-pass', 'request header');
  115. $app = $this->getMockBuilder(MiddlewareApplication::class)
  116. ->setMethods(['pluginBootstrap', 'pluginEvents', 'pluginMiddleware'])
  117. ->setConstructorArgs([$this->config])
  118. ->getMock();
  119. $app->expects($this->at(0))
  120. ->method('pluginBootstrap');
  121. $app->expects($this->at(1))
  122. ->method('pluginEvents')
  123. ->will($this->returnCallback(function ($events) {
  124. return $events;
  125. }));
  126. $app->expects($this->at(2))
  127. ->method('pluginMiddleware')
  128. ->with($this->isInstanceOf(MiddlewareQueue::class))
  129. ->will($this->returnCallback(function ($middleware) {
  130. return $middleware;
  131. }));
  132. $server = new Server($app);
  133. $res = $server->run($request, $response);
  134. $this->assertEquals(
  135. 'source header',
  136. $res->getHeaderLine('X-testing'),
  137. 'Input response is carried through out middleware'
  138. );
  139. $this->assertEquals(
  140. 'request header',
  141. $res->getHeaderLine('X-pass'),
  142. 'Request is used in middleware'
  143. );
  144. }
  145. /**
  146. * test run building a request from globals.
  147. *
  148. * @return void
  149. */
  150. public function testRunWithGlobals()
  151. {
  152. $_SERVER['HTTP_X_PASS'] = 'globalvalue';
  153. $app = new MiddlewareApplication($this->config);
  154. $server = new Server($app);
  155. $res = $server->run();
  156. $this->assertEquals(
  157. 'globalvalue',
  158. $res->getHeaderLine('X-pass'),
  159. 'Default request is made from server'
  160. );
  161. }
  162. /**
  163. * Test an application failing to build middleware properly
  164. *
  165. * @return void
  166. */
  167. public function testRunWithApplicationNotMakingMiddleware()
  168. {
  169. $this->expectException(RuntimeException::class);
  170. $this->expectExceptionMessage('The application `middleware` method');
  171. $app = new InvalidMiddlewareApplication($this->config);
  172. $server = new Server($app);
  173. $server->run();
  174. }
  175. /**
  176. * Test middleware being invoked.
  177. *
  178. * @return void
  179. */
  180. public function testRunMultipleMiddlewareSuccess()
  181. {
  182. $app = new MiddlewareApplication($this->config);
  183. $server = new Server($app);
  184. $res = $server->run();
  185. $this->assertSame('first', $res->getHeaderLine('X-First'));
  186. $this->assertSame('second', $res->getHeaderLine('X-Second'));
  187. }
  188. /**
  189. * Test middleware not creating a response.
  190. *
  191. * @return void
  192. */
  193. public function testRunMiddlewareNoResponse()
  194. {
  195. $this->expectException(RuntimeException::class);
  196. $this->expectExceptionMessage('Application did not create a response. Got "Not a response" instead.');
  197. $app = new BadResponseApplication($this->config);
  198. $server = new Server($app);
  199. $server->run();
  200. }
  201. /**
  202. * Test application events.
  203. *
  204. * @return void
  205. */
  206. public function testRunEvents()
  207. {
  208. $manager = new EventManager();
  209. $manager->setEventList(new EventList());
  210. $app = new EventApplication($this->config, $manager);
  211. $server = new Server($app);
  212. $res = $server->run();
  213. $this->assertCount(1, $manager->listeners('My.event'));
  214. $this->assertEventFired('Server.buildMiddleware', $manager);
  215. $this->assertInstanceOf(ResponseInterface::class, $res);
  216. }
  217. /**
  218. * Test that emit invokes the appropriate methods on the emitter.
  219. *
  220. * @return void
  221. */
  222. public function testEmit()
  223. {
  224. $response = new Response('php://memory', 200, ['x-testing' => 'source header']);
  225. $final = $response
  226. ->withHeader('X-First', 'first')
  227. ->withHeader('X-Second', 'second');
  228. $emitter = $this->getMockBuilder('Zend\Diactoros\Response\EmitterInterface')->getMock();
  229. $emitter->expects($this->once())
  230. ->method('emit')
  231. ->with($final);
  232. $app = new MiddlewareApplication($this->config);
  233. $server = new Server($app);
  234. $server->emit($server->run(null, $response), $emitter);
  235. }
  236. /**
  237. * Test that emit invokes the appropriate methods on the emitter.
  238. *
  239. * @return void
  240. */
  241. public function testEmitCallbackStream()
  242. {
  243. $GLOBALS['mockedHeadersSent'] = false;
  244. $response = new Response('php://memory', 200, ['x-testing' => 'source header']);
  245. $response = $response->withBody(new CallbackStream(function () {
  246. echo 'body content';
  247. }));
  248. $app = new MiddlewareApplication($this->config);
  249. $server = new Server($app);
  250. ob_start();
  251. $server->emit($response);
  252. $result = ob_get_clean();
  253. $this->assertEquals('body content', $result);
  254. }
  255. /**
  256. * Ensure that the Server.buildMiddleware event is fired.
  257. *
  258. * @return void
  259. */
  260. public function testBuildMiddlewareEvent()
  261. {
  262. $app = new MiddlewareApplication($this->config);
  263. $server = new Server($app);
  264. $this->called = false;
  265. $server->getEventManager()->on('Server.buildMiddleware', function (Event $event, $middleware) {
  266. $this->assertInstanceOf('Cake\Http\MiddlewareQueue', $middleware);
  267. $middleware->add(function ($req, $res, $next) {
  268. $this->called = true;
  269. return $next($req, $res);
  270. });
  271. $this->middleware = $middleware;
  272. });
  273. $server->run();
  274. $this->assertTrue($this->called, 'Middleware added in the event was not triggered.');
  275. $this->assertInstanceOf('Closure', $this->middleware->get(3), '2nd last middleware is a closure');
  276. $this->assertSame($app, $this->middleware->get(4), 'Last middleware is an app instance');
  277. }
  278. /**
  279. * test event manager proxies to the application.
  280. *
  281. * @return void
  282. */
  283. public function testEventManagerProxies()
  284. {
  285. $app = $this->getMockForAbstractClass(
  286. BaseApplication::class,
  287. [$this->config]
  288. );
  289. $server = new Server($app);
  290. $this->assertSame($app->getEventManager(), $server->getEventManager());
  291. }
  292. /**
  293. * test event manager cannot be set on applications without events.
  294. *
  295. * @return void
  296. */
  297. public function testGetEventManagerNonEventedApplication()
  298. {
  299. $app = $this->createMock(HttpApplicationInterface::class);
  300. $server = new Server($app);
  301. $this->assertSame(EventManager::instance(), $server->getEventManager());
  302. }
  303. /**
  304. * test event manager cannot be set on applications without events.
  305. *
  306. * @return void
  307. */
  308. public function testSetEventManagerNonEventedApplication()
  309. {
  310. $this->expectException(InvalidArgumentException::class);
  311. $app = $this->createMock(HttpApplicationInterface::class);
  312. $events = new EventManager();
  313. $server = new Server($app);
  314. $server->setEventManager($events);
  315. }
  316. }