ExternalTest.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. <?php
  2. /**
  3. * Unit tests for external request client
  4. *
  5. * @group ko7
  6. * @group ko7.request
  7. * @group ko7.request.client
  8. * @group ko7.request.client.external
  9. *
  10. * @package KO7\Tests
  11. *
  12. * @copyright (c) 2007-2016 Kohana Team
  13. * @copyright (c) since 2016 Koseven Team
  14. * @license https://koseven.dev/LICENSE
  15. */
  16. use Pagely\Component\HttpMock\PHPUnit\HttpMockTrait;
  17. class KO7_Request_Client_ExternalTest extends Unittest_TestCase {
  18. /**
  19. * We need a fake HTTP Server for this one
  20. */
  21. use HttpMockTrait;
  22. /**
  23. * Host we setup our fake server (you probably don't need to change this)
  24. *
  25. * @var string
  26. */
  27. public static $host = '127.0.0.1';
  28. /**
  29. * Port our fake server will run on (you maybe need to change this to another one)
  30. * Default is 7507 because according to Wikipedia it has no use by another software
  31. *
  32. * @var int
  33. */
  34. public static $port = 7507;
  35. /**
  36. * Setup fake HTTP Server
  37. */
  38. public static function setUpBeforeClass() : void
  39. {
  40. static::setUpHttpMockBeforeClass(static::$port, static::$host);
  41. parent::setUpBeforeClass();
  42. }
  43. /**
  44. * Shutdown HTTP Server
  45. */
  46. public static function tearDownAfterClass() : void
  47. {
  48. static::tearDownHttpMockAfterClass();
  49. parent::tearDownAfterClass();
  50. }
  51. /**
  52. * Check if Server works and start it
  53. * @throws KO7_Exception
  54. * @throws ReflectionException
  55. */
  56. public function setUp() : void
  57. {
  58. $this->setUpHttpMock();
  59. parent::setUp();
  60. }
  61. /**
  62. * Kill Server
  63. * @throws KO7_Exception
  64. * @throws ReflectionException
  65. */
  66. public function tearDown() : void
  67. {
  68. $this->tearDownHttpMock();
  69. parent::tearDown();
  70. }
  71. /**
  72. * Provides test data for test_external_requests
  73. *
  74. * Note: We test GET and POST requests
  75. *
  76. * @return array
  77. */
  78. public function provider_external_requests() : array
  79. {
  80. // Test Stream Client
  81. $return = [
  82. [
  83. 'client' => 'Request_Client_Stream',
  84. 'method' => HTTP_Request::GET,
  85. 'options' => [
  86. 'http' => [
  87. 'user_agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1'
  88. ]
  89. ]
  90. ],
  91. // This will fail since our stream is not write-able
  92. [
  93. 'client' => 'Request_Client_Stream',
  94. 'method' => HTTP_Request::POST,
  95. 'options' => [],
  96. 'status' => 200,
  97. 'exception' => TRUE
  98. ],
  99. ];
  100. // Test curl client if php curl extension is loaded
  101. if (extension_loaded('curl'))
  102. {
  103. $return[] =
  104. [
  105. 'client' => 'Request_Client_Curl',
  106. 'method' => HTTP_Request::GET,
  107. 'options' => [
  108. constant('CURLOPT_TIMEOUT') => 1200000,
  109. constant('CURLOPT_USERAGENT') => 'spider'
  110. ]
  111. ];
  112. $return[] =
  113. [
  114. 'client' => 'Request_Client_Curl',
  115. 'method' => HTTP_Request::POST,
  116. 'options' => [
  117. constant('CURLOPT_TIMEOUT') => 1200000,
  118. constant('CURLOPT_USERAGENT') => 'spider'
  119. ]
  120. ];
  121. // Test with invalid port
  122. $return[] =
  123. [
  124. 'client' => 'Request_Client_Curl',
  125. 'method' => HTTP_Request::GET,
  126. 'options' => [
  127. constant('CURLOPT_PORT') => 111
  128. ],
  129. 'status' => 200,
  130. 'exception' => TRUE
  131. ];
  132. // Test with invalid options
  133. $return[] =
  134. [
  135. 'client' => 'Request_Client_Curl',
  136. 'method' => HTTP_Request::GET,
  137. 'options' => [
  138. 'invalid option' => 'this is not valid'
  139. ],
  140. 'status' => 200,
  141. 'exception' => TRUE
  142. ];
  143. }
  144. // Test curl client if pecl_http extension is loaded
  145. if (extension_loaded('http'))
  146. {
  147. $return[] =
  148. [
  149. 'client' => 'Request_Client_HTTP',
  150. 'method' => HTTP_Request::GET,
  151. 'options' => [
  152. 'timeout' => 1200000
  153. ]
  154. ];
  155. $return[] =
  156. [
  157. 'client' => 'Request_Client_HTTP',
  158. 'method' => HTTP_Request::POST,
  159. 'options' => [
  160. 'timeout' => 1200000
  161. ]
  162. ];
  163. // Test with invalid port
  164. $return[] =
  165. [
  166. 'client' => 'Request_Client_HTTP',
  167. 'method' => HTTP_Request::GET,
  168. 'options' => [
  169. 'port' => '11112'
  170. ],
  171. 'status' => 200,
  172. 'exception' => TRUE
  173. ];
  174. }
  175. return $return;
  176. }
  177. /**
  178. * Tests Request::factory to a external source (Request_Client_External)
  179. *
  180. * @dataProvider provider_external_requests
  181. *
  182. * @param string $client Client Class to use (has to extend Request_Client_External)
  183. * @param string $method GET/POST/PUT/DELETE
  184. * @param array $options Additional Options (curl, stream options, etc..) e.g CURLOPT_TIMEOUT
  185. * @param int $status Status code the request shall return (200, 301, 404, etc..)
  186. * @param bool $exception Expect an exception
  187. *
  188. * @throws Request_Exception
  189. */
  190. public function test_external_requests(string $client, string $method, array $options, int $status = 200, $exception = false) : void
  191. {
  192. // Wee ned to increase our memory size for this test (we will reset this one at the end)
  193. $initialLimit = ini_get('memory_limit');
  194. ini_set('memory_limit','1024M');
  195. // Expose KO7 and send it's UA
  196. KO7::$expose = TRUE;
  197. // Setup the Mocking Server
  198. $server = $this->http->mock;
  199. // Start creating the response, set method and path
  200. $server = $server->when()->methodIs($method)->pathIs('/test');
  201. // Only accept if certain queries are send correctly
  202. $queries = [
  203. 'test' => 'value',
  204. 'test2' => 'value2'
  205. ];
  206. $server = $server->queryParamsAre($queries);
  207. // Only accept if following headers are sent
  208. $headers = [
  209. 'X-Sent-Header' => 'Xs Value',
  210. 'Y-Sent-Header' => 'Ys Value'
  211. ];
  212. foreach ($headers as $header => $value)
  213. {
  214. $server = $server->headerIs($header, $value);
  215. }
  216. // Start Response Configuration and add Status Code
  217. $server = $server->then()->statusCode($status);
  218. // Set Response header - we do this so we can verify that they get parsed correctly in the response
  219. $responseHeaders = [
  220. 'X-Return-Header' => 'Xr Value',
  221. 'Y-Return-Header' => 'Yr Value'
  222. ];
  223. foreach ($responseHeaders as $header => $value)
  224. {
  225. $server = $server->header($header, $value);
  226. }
  227. // Set what the server shall return in case of the above request comes in
  228. $expectedBody = 'This is a ' . $method . ' request.';
  229. $server->body($expectedBody)->end();
  230. // Finish Server Setup
  231. $this->http->setUp();
  232. // Set the Request client
  233. Request_Client_External::$client = $client;
  234. // Start a request to the server with given client
  235. try
  236. {
  237. $request = Request::factory('http://' . static::$host . ':' . static::$port . '/test', $options);
  238. }
  239. catch (Request_Exception $e)
  240. {
  241. $this->fail($e->getMessage());
  242. }
  243. // Set Request Method, Body, and cookies
  244. $request->method($method);
  245. $request->body('Send this body');
  246. $request->cookie('Test Cookie', 'test');
  247. // Add a Post Parameter if request is post
  248. if ($method === HTTP_Request::POST)
  249. {
  250. $request->post('post-param1', 'value');
  251. }
  252. // Add query to the request
  253. foreach ($queries as $query => $value)
  254. {
  255. $request->query($query, $value);
  256. }
  257. // Send headers
  258. $request->headers($headers);
  259. // Execute request
  260. try
  261. {
  262. $response = $request->execute();
  263. }
  264. catch (HTTP_Exception_404 | Request_Exception $e)
  265. {
  266. if ($exception && $e instanceof Request_Exception)
  267. {
  268. return;
  269. }
  270. $this->fail($e->getMessage());
  271. }
  272. // Parse Header
  273. $expected_header = array_change_key_case($responseHeaders, CASE_LOWER);
  274. $actual_headers = array_intersect_key($response->headers()->getArrayCopy(), $expected_header);
  275. // Check if response body is correct
  276. $this->assertSame($expectedBody, $response->body());
  277. // Check if response status is correct
  278. $this->assertSame($status, $response->status());
  279. // Check if response header are correct
  280. $this->assertSame($expected_header, $actual_headers);
  281. // Reset Memory Limit to initial one
  282. ini_set('memory_limit',$initialLimit);
  283. }
  284. public function provider_test_options() : array
  285. {
  286. return [
  287. [
  288. 'key' => 'Test',
  289. [
  290. 'Test' => 'Koseven'
  291. ],
  292. 'value' => 'Koseven'
  293. ],
  294. [
  295. [
  296. 'Test' => 'Koseven',
  297. 'Test2' => 'Koseven 2'
  298. ],
  299. [
  300. 'Test' => 'Koseven',
  301. 'Test2' => 'Koseven 2'
  302. ]
  303. ]
  304. ];
  305. }
  306. /**
  307. * Tests Request_Client_External::setOptions
  308. *
  309. * @dataProvider provider_test_options
  310. *
  311. * @param mixed $key The option to set/get
  312. * @param array $expected Expected Result
  313. * @param string $value The options value
  314. */
  315. public function test_options($key, array $expected, $value = NULL) : void
  316. {
  317. // Initialize Client
  318. try
  319. {
  320. $client = KO7_Request_Client_External::factory([], 'Request_Client_Stream');
  321. }
  322. catch (Request_Exception $e)
  323. {
  324. $this->fail('Could not initialize External Client. Error: ' . $e->getMessage());
  325. }
  326. // Set Options
  327. $client->options($key, $value);
  328. // Get all options and compare arrays
  329. $this->assertSame($expected, $client->options());
  330. // Get specific option and check if value is correct
  331. if (is_array($key))
  332. {
  333. foreach ($key as $k => $val)
  334. {
  335. $this->assertSame($val, $client->options($k));
  336. }
  337. }
  338. else
  339. {
  340. $this->assertSame($value, $client->options($key));
  341. }
  342. }
  343. /**
  344. * Test Request_Client_External::factory
  345. *
  346. * This test checks if Exception is thrown when we pass and Invalid client
  347. *
  348. */
  349. public function test_invalid_request_class() : void
  350. {
  351. // Expect Exception
  352. $this->expectException(Request_Exception::class);
  353. // Try to use it
  354. Request_Client_External::factory([], 'Arr');
  355. }
  356. }