StreamTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  10. * @link https://cakephp.org CakePHP(tm) Project
  11. * @since 3.0.0
  12. * @license https://opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Cake\Test\TestCase\Http\Client\Adapter;
  15. use Cake\Http\Client\Adapter\Stream;
  16. use Cake\Http\Client\Request;
  17. use Cake\TestSuite\TestCase;
  18. /**
  19. * CakeStreamWrapper class
  20. */
  21. class CakeStreamWrapper implements \ArrayAccess
  22. {
  23. private $_stream;
  24. private $_query = [];
  25. private $_data = [
  26. 'headers' => [
  27. 'HTTP/1.1 200 OK',
  28. ],
  29. ];
  30. public function stream_open($path, $mode, $options, &$openedPath)
  31. {
  32. if ($path == 'http://throw_exception/') {
  33. throw new \Exception();
  34. }
  35. $query = parse_url($path, PHP_URL_QUERY);
  36. if ($query) {
  37. parse_str($query, $this->_query);
  38. }
  39. $this->_stream = fopen('php://memory', 'rb+');
  40. fwrite($this->_stream, str_repeat('x', 20000));
  41. rewind($this->_stream);
  42. return true;
  43. }
  44. public function stream_close()
  45. {
  46. return fclose($this->_stream);
  47. }
  48. public function stream_read($count)
  49. {
  50. if (isset($this->_query['sleep'])) {
  51. sleep(1);
  52. }
  53. return fread($this->_stream, $count);
  54. }
  55. public function stream_eof()
  56. {
  57. return feof($this->_stream);
  58. }
  59. public function stream_set_option($option, $arg1, $arg2)
  60. {
  61. return false;
  62. }
  63. public function offsetExists($offset)
  64. {
  65. return isset($this->_data[$offset]);
  66. }
  67. public function offsetGet($offset)
  68. {
  69. return $this->_data[$offset];
  70. }
  71. public function offsetSet($offset, $value)
  72. {
  73. $this->_data[$offset] = $value;
  74. }
  75. public function offsetUnset($offset)
  76. {
  77. unset($this->_data[$offset]);
  78. }
  79. }
  80. /**
  81. * HTTP stream adapter test.
  82. */
  83. class StreamTest extends TestCase
  84. {
  85. public function setUp()
  86. {
  87. parent::setUp();
  88. $this->stream = $this->getMockBuilder('Cake\Http\Client\Adapter\Stream')
  89. ->setMethods(['_send'])
  90. ->getMock();
  91. stream_wrapper_unregister('http');
  92. stream_wrapper_register('http', __NAMESPACE__ . '\CakeStreamWrapper');
  93. }
  94. public function tearDown()
  95. {
  96. parent::tearDown();
  97. stream_wrapper_restore('http');
  98. }
  99. /**
  100. * Test the send method
  101. *
  102. * @return void
  103. */
  104. public function testSend()
  105. {
  106. $stream = new Stream();
  107. $request = new Request('http://localhost', 'GET', [
  108. 'User-Agent' => 'CakePHP TestSuite',
  109. 'Cookie' => 'testing=value',
  110. ]);
  111. try {
  112. $responses = $stream->send($request, []);
  113. } catch (\Cake\Core\Exception\Exception $e) {
  114. $this->markTestSkipped('Could not connect to localhost, skipping');
  115. }
  116. $this->assertInstanceOf('Cake\Http\Client\Response', $responses[0]);
  117. }
  118. /**
  119. * Test the send method by using cakephp:// protocol.
  120. *
  121. * @return void
  122. */
  123. public function testSendByUsingCakephpProtocol()
  124. {
  125. $stream = new Stream();
  126. $request = new Request('http://dummy/');
  127. $responses = $stream->send($request, []);
  128. $this->assertInstanceOf('Cake\Http\Client\Response', $responses[0]);
  129. $this->assertEquals(20000, strlen($responses[0]->getStringBody()));
  130. }
  131. /**
  132. * Test stream error_handler cleanup when wrapper throws exception
  133. *
  134. * @return void
  135. */
  136. public function testSendWrapperException()
  137. {
  138. $stream = new Stream();
  139. $request = new Request('http://throw_exception/');
  140. $currentHandler = set_error_handler(function () {
  141. });
  142. restore_error_handler();
  143. try {
  144. $stream->send($request, []);
  145. } catch (\Exception $e) {
  146. }
  147. $newHandler = set_error_handler(function () {
  148. });
  149. restore_error_handler();
  150. $this->assertEquals($currentHandler, $newHandler);
  151. }
  152. /**
  153. * Test building the context headers
  154. *
  155. * @return void
  156. */
  157. public function testBuildingContextHeader()
  158. {
  159. $request = new Request(
  160. 'http://localhost',
  161. 'GET',
  162. [
  163. 'User-Agent' => 'CakePHP TestSuite',
  164. 'Content-Type' => 'application/json',
  165. 'Cookie' => 'a=b; c=do%20it',
  166. ]
  167. );
  168. $options = [
  169. 'redirect' => 20,
  170. ];
  171. $this->stream->send($request, $options);
  172. $result = $this->stream->contextOptions();
  173. $expected = [
  174. 'User-Agent: CakePHP TestSuite',
  175. 'Content-Type: application/json',
  176. 'Cookie: a=b; c=do%20it',
  177. 'Connection: close',
  178. ];
  179. $this->assertEquals(implode("\r\n", $expected), $result['header']);
  180. $this->assertSame(0, $result['max_redirects']);
  181. $this->assertTrue($result['ignore_errors']);
  182. }
  183. /**
  184. * Test send() + context options with string content.
  185. *
  186. * @return void
  187. */
  188. public function testSendContextContentString()
  189. {
  190. $content = json_encode(['a' => 'b']);
  191. $request = new Request(
  192. 'http://localhost',
  193. 'GET',
  194. ['Content-Type' => 'application/json'],
  195. $content
  196. );
  197. $options = [
  198. 'redirect' => 20,
  199. ];
  200. $this->stream->send($request, $options);
  201. $result = $this->stream->contextOptions();
  202. $expected = [
  203. 'Content-Type: application/json',
  204. 'Connection: close',
  205. 'User-Agent: CakePHP',
  206. ];
  207. $this->assertEquals(implode("\r\n", $expected), $result['header']);
  208. $this->assertEquals($content, $result['content']);
  209. }
  210. /**
  211. * Test send() + context options with array content.
  212. *
  213. * @return void
  214. */
  215. public function testSendContextContentArray()
  216. {
  217. $request = new Request(
  218. 'http://localhost',
  219. 'GET',
  220. [
  221. 'Content-Type' => 'application/json',
  222. ],
  223. ['a' => 'my value']
  224. );
  225. $this->stream->send($request, []);
  226. $result = $this->stream->contextOptions();
  227. $expected = [
  228. 'Content-Type: application/x-www-form-urlencoded',
  229. 'Connection: close',
  230. 'User-Agent: CakePHP',
  231. ];
  232. $this->assertStringStartsWith(implode("\r\n", $expected), $result['header']);
  233. $this->assertContains('a=my+value', $result['content']);
  234. $this->assertContains('my+value', $result['content']);
  235. }
  236. /**
  237. * Test send() + context options with array content.
  238. *
  239. * @return void
  240. */
  241. public function testSendContextContentArrayFiles()
  242. {
  243. $request = new Request(
  244. 'http://localhost',
  245. 'GET',
  246. ['Content-Type' => 'application/json'],
  247. ['upload' => fopen(CORE_PATH . 'VERSION.txt', 'r')]
  248. );
  249. $this->stream->send($request, []);
  250. $result = $this->stream->contextOptions();
  251. $this->assertContains("Content-Type: multipart/form-data", $result['header']);
  252. $this->assertContains("Connection: close\r\n", $result['header']);
  253. $this->assertContains("User-Agent: CakePHP", $result['header']);
  254. $this->assertContains('name="upload"', $result['content']);
  255. $this->assertContains('filename="VERSION.txt"', $result['content']);
  256. }
  257. /**
  258. * Test send() + context options for SSL.
  259. *
  260. * @return void
  261. */
  262. public function testSendContextSsl()
  263. {
  264. $request = new Request('https://localhost.com/test.html');
  265. $options = [
  266. 'ssl_verify_host' => true,
  267. 'ssl_verify_peer' => true,
  268. 'ssl_verify_peer_name' => true,
  269. 'ssl_verify_depth' => 9000,
  270. 'ssl_allow_self_signed' => false,
  271. 'proxy' => [
  272. 'proxy' => '127.0.0.1:8080',
  273. ],
  274. ];
  275. $this->stream->send($request, $options);
  276. $result = $this->stream->contextOptions();
  277. $expected = [
  278. 'peer_name' => 'localhost.com',
  279. 'verify_peer' => true,
  280. 'verify_peer_name' => true,
  281. 'verify_depth' => 9000,
  282. 'allow_self_signed' => false,
  283. 'proxy' => '127.0.0.1:8080',
  284. ];
  285. foreach ($expected as $k => $v) {
  286. $this->assertEquals($v, $result[$k]);
  287. }
  288. $this->assertIsReadable($result['cafile']);
  289. }
  290. /**
  291. * Test send() + context options for SSL.
  292. *
  293. * @return void
  294. */
  295. public function testSendContextSslNoVerifyPeerName()
  296. {
  297. $request = new Request('https://localhost.com/test.html');
  298. $options = [
  299. 'ssl_verify_host' => true,
  300. 'ssl_verify_peer' => true,
  301. 'ssl_verify_peer_name' => false,
  302. 'ssl_verify_depth' => 9000,
  303. 'ssl_allow_self_signed' => false,
  304. 'proxy' => [
  305. 'proxy' => '127.0.0.1:8080',
  306. ],
  307. ];
  308. $this->stream->send($request, $options);
  309. $result = $this->stream->contextOptions();
  310. $expected = [
  311. 'peer_name' => 'localhost.com',
  312. 'verify_peer' => true,
  313. 'verify_peer_name' => false,
  314. 'verify_depth' => 9000,
  315. 'allow_self_signed' => false,
  316. 'proxy' => '127.0.0.1:8080',
  317. ];
  318. foreach ($expected as $k => $v) {
  319. $this->assertEquals($v, $result[$k]);
  320. }
  321. $this->assertIsReadable($result['cafile']);
  322. }
  323. /**
  324. * The PHP stream API returns ALL the headers for ALL the requests when
  325. * there are redirects.
  326. *
  327. * @return void
  328. */
  329. public function testCreateResponseWithRedirects()
  330. {
  331. $headers = [
  332. 'HTTP/1.1 302 Found',
  333. 'Date: Mon, 31 Dec 2012 16:53:16 GMT',
  334. 'Server: Apache/2.2.22 (Unix) DAV/2 PHP/5.4.9 mod_ssl/2.2.22 OpenSSL/0.9.8r',
  335. 'X-Powered-By: PHP/5.4.9',
  336. 'Location: http://localhost/cake3/tasks/second',
  337. 'Content-Length: 0',
  338. 'Connection: close',
  339. 'Content-Type: text/html; charset=UTF-8',
  340. 'Set-Cookie: first=value',
  341. 'HTTP/1.1 302 Found',
  342. 'Date: Mon, 31 Dec 2012 16:53:16 GMT',
  343. 'Server: Apache/2.2.22 (Unix) DAV/2 PHP/5.4.9 mod_ssl/2.2.22 OpenSSL/0.9.8r',
  344. 'X-Powered-By: PHP/5.4.9',
  345. 'Location: http://localhost/cake3/tasks/third',
  346. 'Content-Length: 0',
  347. 'Connection: close',
  348. 'Content-Type: text/html; charset=UTF-8',
  349. 'Set-Cookie: second=val',
  350. 'HTTP/1.1 200 OK',
  351. 'Date: Mon, 31 Dec 2012 16:53:16 GMT',
  352. 'Server: Apache/2.2.22 (Unix) DAV/2 PHP/5.4.9 mod_ssl/2.2.22 OpenSSL/0.9.8r',
  353. 'X-Powered-By: PHP/5.4.9',
  354. 'Content-Length: 22',
  355. 'Connection: close',
  356. 'Content-Type: text/html; charset=UTF-8',
  357. 'Set-Cookie: third=works',
  358. ];
  359. $content = 'This is the third page';
  360. $responses = $this->stream->createResponses($headers, $content);
  361. $this->assertCount(3, $responses);
  362. $this->assertEquals('close', $responses[0]->getHeaderLine('Connection'));
  363. $this->assertEquals('', (string)$responses[0]->getBody());
  364. $this->assertEquals('', (string)$responses[1]->getBody());
  365. $this->assertEquals($content, (string)$responses[2]->getBody());
  366. $this->assertEquals(302, $responses[0]->getStatusCode());
  367. $this->assertEquals(302, $responses[1]->getStatusCode());
  368. $this->assertEquals(200, $responses[2]->getStatusCode());
  369. $this->assertEquals('value', $responses[0]->getCookie('first'));
  370. $this->assertNull($responses[0]->getCookie('second'));
  371. $this->assertNull($responses[0]->getCookie('third'));
  372. $this->assertNull($responses[1]->getCookie('first'));
  373. $this->assertEquals('val', $responses[1]->getCookie('second'));
  374. $this->assertNull($responses[1]->getCookie('third'));
  375. $this->assertNull($responses[2]->getCookie('first'));
  376. $this->assertNull($responses[2]->getCookie('second'));
  377. $this->assertEquals('works', $responses[2]->getCookie('third'));
  378. }
  379. /**
  380. * Test that no exception is radied when not timed out.
  381. *
  382. * @return void
  383. */
  384. public function testKeepDeadline()
  385. {
  386. $request = new Request('http://dummy/?sleep');
  387. $options = [
  388. 'timeout' => 5,
  389. ];
  390. $t = microtime(true);
  391. $stream = new Stream();
  392. $stream->send($request, $options);
  393. $this->assertLessThan(5, microtime(true) - $t);
  394. }
  395. /**
  396. * Test that an exception is raised when timed out.
  397. *
  398. * @return void
  399. */
  400. public function testMissDeadline()
  401. {
  402. $this->expectException(\Cake\Http\Exception\HttpException::class);
  403. $this->expectExceptionMessage('Connection timed out http://dummy/?sleep');
  404. $request = new Request('http://dummy/?sleep');
  405. $options = [
  406. 'timeout' => 2,
  407. ];
  408. $stream = new Stream();
  409. $stream->send($request, $options);
  410. }
  411. }