CommonHttpTests.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Http
  17. * @subpackage UnitTests
  18. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. // Read local configuration
  23. if (! defined('TESTS_ZEND_HTTP_CLIENT_BASEURI') &&
  24. is_readable('TestConfiguration.php')) {
  25. require_once 'TestConfiguration.php';
  26. }
  27. require_once 'Zend/Http/Client.php';
  28. require_once 'Zend/Uri/Http.php';
  29. /**
  30. * This Testsuite includes all Zend_Http_Client that require a working web
  31. * server to perform. It was designed to be extendable, so that several
  32. * test suites could be run against several servers, with different client
  33. * adapters and configurations.
  34. *
  35. * Note that $this->baseuri must point to a directory on a web server
  36. * containing all the files under the _files directory. You should symlink
  37. * or copy these files and set 'baseuri' properly.
  38. *
  39. * You can also set the proper constant in your test configuration file to
  40. * point to the right place.
  41. *
  42. * @category Zend
  43. * @package Zend_Http_Client
  44. * @subpackage UnitTests
  45. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  46. * @license http://framework.zend.com/license/new-bsd New BSD License
  47. * @group Zend_Http
  48. * @group Zend_Http_Client
  49. */
  50. abstract class Zend_Http_Client_CommonHttpTests extends PHPUnit_Framework_TestCase
  51. {
  52. /**
  53. * The bast URI for this test, containing all files in the _files directory
  54. * Should be set in TestConfiguration.php or TestConfiguration.php.dist
  55. *
  56. * @var string
  57. */
  58. protected $baseuri;
  59. /**
  60. * Common HTTP client
  61. *
  62. * @var Zend_Http_Client
  63. */
  64. protected $client = null;
  65. /**
  66. * Common HTTP client adapter
  67. *
  68. * @var Zend_Http_Client_Adapter_Interface
  69. */
  70. protected $_adapter = null;
  71. /**
  72. * Configuration array
  73. *
  74. * @var array
  75. */
  76. protected $config = array(
  77. 'adapter' => 'Zend_Http_Client_Adapter_Socket'
  78. );
  79. /**
  80. * Set up the test case
  81. *
  82. */
  83. protected function setUp()
  84. {
  85. if (defined('TESTS_ZEND_HTTP_CLIENT_BASEURI') &&
  86. Zend_Uri_Http::check(TESTS_ZEND_HTTP_CLIENT_BASEURI)) {
  87. $this->baseuri = TESTS_ZEND_HTTP_CLIENT_BASEURI;
  88. if (substr($this->baseuri, -1) != '/') $this->baseuri .= '/';
  89. $name = $this->getName();
  90. if (($pos = strpos($name, ' ')) !== false) {
  91. $name = substr($name, 0, $pos);
  92. }
  93. $uri = $this->baseuri . $name . '.php';
  94. $this->_adapter = new $this->config['adapter'];
  95. $this->client = new Zend_Http_Client($uri, $this->config);
  96. $this->client->setAdapter($this->_adapter);
  97. } else {
  98. // Skip tests
  99. $this->markTestSkipped("Zend_Http_Client dynamic tests are not enabled in TestConfiguration.php");
  100. }
  101. }
  102. /**
  103. * Clean up the test environment
  104. *
  105. */
  106. protected function tearDown()
  107. {
  108. $this->client = null;
  109. $this->_adapter = null;
  110. }
  111. /**
  112. * Simple request tests
  113. */
  114. /**
  115. * Test simple requests
  116. *
  117. */
  118. public function testSimpleRequests()
  119. {
  120. $methods = array('GET', 'POST', 'OPTIONS', 'PUT', 'DELETE');
  121. foreach ($methods as $method) {
  122. $res = $this->client->request($method);
  123. $this->assertEquals('Success', $res->getBody(), "HTTP {$method} request failed.");
  124. }
  125. }
  126. /**
  127. * Test we can get the last request as string
  128. *
  129. */
  130. public function testGetLastRequest()
  131. {
  132. $this->client->setUri($this->baseuri . 'testHeaders.php');
  133. $this->client->setParameterGet('someinput', 'somevalue');
  134. $this->client->setHeaders(array(
  135. 'X-Powered-By' => 'My Glorious Golden Ass',
  136. ));
  137. $res = $this->client->request(Zend_Http_Client::TRACE);
  138. if ($res->getStatus() == 405 || $res->getStatus() == 501) {
  139. $this->markTestSkipped("Server does not allow the TRACE method");
  140. }
  141. $this->assertEquals($this->client->getLastRequest(), $res->getBody(), 'Response body should be exactly like the last request');
  142. }
  143. /**
  144. * GET and POST parameters tests
  145. */
  146. /**
  147. * Test we can properly send GET parameters
  148. *
  149. * @dataProvider parameterArrayProvider
  150. */
  151. public function testGetData($params)
  152. {
  153. $this->client->setUri($this->client->getUri(true) . '?name=Arthur');
  154. $this->client->setParameterGet($params);
  155. $res = $this->client->request('GET');
  156. $this->assertEquals(serialize(array_merge(array('name' => 'Arthur'), $params)), $res->getBody());
  157. }
  158. /**
  159. * Test we can properly send POST parameters with
  160. * application/x-www-form-urlencoded content type
  161. *
  162. * @dataProvider parameterArrayProvider
  163. */
  164. public function testPostDataUrlEncoded($params)
  165. {
  166. $this->client->setUri($this->baseuri . 'testPostData.php');
  167. $this->client->setEncType(Zend_Http_Client::ENC_URLENCODED);
  168. $this->client->setParameterPost($params);
  169. $res = $this->client->request('POST');
  170. $this->assertEquals(serialize($params), $res->getBody(), "POST data integrity test failed");
  171. }
  172. /**
  173. * Test we can properly send PUT parameters with
  174. * application/x-www-form-urlencoded content type
  175. *
  176. * @dataProvider parameterArrayProvider
  177. */
  178. public function testPutDataUrlEncoded($params)
  179. {
  180. $this->client->setUri($this->baseuri . 'testPutData.php');
  181. $this->client->setEncType(Zend_Http_Client::ENC_URLENCODED);
  182. $this->client->setParameterPost($params);
  183. $res = $this->client->request('PUT');
  184. $this->assertEquals(serialize($params), $res->getBody(), "PUT data integrity test failed");
  185. }
  186. /**
  187. * Test we can properly send PUT parameters without
  188. * content type, relying on default content type (urlencoded)
  189. *
  190. * @dataProvider parameterArrayProvider
  191. */
  192. public function testPutDataDefault($params)
  193. {
  194. $this->client->setUri($this->baseuri . 'testPutData.php');
  195. // note that no content type is set
  196. $this->client->setParameterPost($params);
  197. $res = $this->client->request('PUT');
  198. $this->assertEquals(serialize($params), $res->getBody(), "PUT data integrity test failed for default content-type");
  199. }
  200. /**
  201. * Test we can properly send parameters with
  202. * application/x-www-form-urlencoded content type
  203. *
  204. * @dataProvider parameterArrayProvider
  205. */
  206. public function testDeleteDataUrlEncoded($params)
  207. {
  208. $this->client->setUri($this->baseuri . 'testDeleteData.php');
  209. $this->client->setEncType(Zend_Http_Client::ENC_URLENCODED);
  210. $this->client->setParameterPost($params);
  211. $res = $this->client->request('DELETE');
  212. $this->assertEquals(serialize($params), $res->getBody(), "DELETE data integrity test failed");
  213. }
  214. /**
  215. * Test we can properly send POST parameters with
  216. * multipart/form-data content type
  217. *
  218. * @dataProvider parameterArrayProvider
  219. */
  220. public function testPostDataMultipart($params)
  221. {
  222. $this->client->setUri($this->baseuri . 'testPostData.php');
  223. $this->client->setEncType(Zend_Http_Client::ENC_FORMDATA);
  224. $this->client->setParameterPost($params);
  225. $res = $this->client->request('POST');
  226. $this->assertEquals(serialize($params), $res->getBody(), "POST data integrity test failed");
  227. }
  228. /**
  229. * Test we can properly send PUT parameters with
  230. * multipart/form-data content type
  231. *
  232. * @dataProvider parameterArrayProvider
  233. */
  234. public function testPutDataMultipart($params)
  235. {
  236. $this->client->setUri($this->baseuri . 'testRawPutData.php');
  237. $this->client->setParameterPost($params);
  238. $this->client->setMethod(Zend_Http_Client::PUT);
  239. $this->client->setEncType(Zend_Http_Client::ENC_FORMDATA);
  240. $response = $this->client->request();
  241. $responseText = $response->getBody();
  242. $this->_checkPresence($responseText, $params);
  243. }
  244. /**
  245. * Checks the presence of keys (non-numeric only) and values
  246. * in the raw form data reponse for a PUT or DELETE request recursively
  247. *
  248. * An example response (I do not know of a better way to check it):
  249. * -----ZENDHTTPCLIENT-c63973519a6bb3ec45495876f5e15828
  250. * Content-Disposition: form-data; name="quest"
  251. *
  252. * To seek the holy grail
  253. * -----ZENDHTTPCLIENT-c63973519a6bb3ec45495876f5e15828
  254. * Content-Disposition: form-data; name="YourMother"
  255. *
  256. * Was a hamster
  257. * -----ZENDHTTPCLIENT-c63973519a6bb3ec45495876f5e15828
  258. * Content-Disposition: form-data; name="specialChars"
  259. *
  260. * <>$+ &?=[]^%
  261. * -----ZENDHTTPCLIENT-c63973519a6bb3ec45495876f5e15828
  262. * Content-Disposition: form-data; name="array[]"
  263. *
  264. * firstItem
  265. * -----ZENDHTTPCLIENT-c63973519a6bb3ec45495876f5e15828
  266. * Content-Disposition: form-data; name="array[]"
  267. *
  268. * secondItem
  269. * -----ZENDHTTPCLIENT-c63973519a6bb3ec45495876f5e15828
  270. * Content-Disposition: form-data; name="array[]"
  271. *
  272. * 3rdItem
  273. * -----ZENDHTTPCLIENT-c63973519a6bb3ec45495876f5e15828--
  274. * @param string $responseText
  275. * @param string|integer|array $needle
  276. */
  277. protected function _checkPresence($responseText, $needle)
  278. {
  279. if (is_array($needle)) {
  280. foreach ($needle as $key => $value) {
  281. // treat array values recursively, let them re-enter this function
  282. if (is_array($value)) {
  283. $this->_checkPresence($responseText, $value);
  284. continue;
  285. }
  286. // continue with non array keys and values
  287. // numeric keys will not be present in the response
  288. if (!is_int($key)) {
  289. $this->assertGreaterThan(
  290. 0,
  291. strpos($responseText, $key),
  292. "key '$key' is missing from the reponse for raw multipart PUT or DELETE request"
  293. );
  294. }
  295. $this->assertGreaterThan(
  296. 0,
  297. strpos($responseText, $value),
  298. "value '$value' is missing from the reponse for raw multipart PUT or DELETE request"
  299. );
  300. }
  301. }
  302. }
  303. /**
  304. * Test we can properly send DELETE parameters with
  305. * multipart/form-data content type
  306. *
  307. * @dataProvider parameterArrayProvider
  308. */
  309. public function testDeleteDataMultipart($params)
  310. {
  311. $this->client->setUri($this->baseuri . 'testRawDeleteData.php');
  312. $this->client->setParameterPost($params);
  313. $this->client->setMethod(Zend_Http_Client::DELETE);
  314. $this->client->setEncType(Zend_Http_Client::ENC_FORMDATA);
  315. $response = $this->client->request();
  316. $responseText = $response->getBody();
  317. $this->_checkPresence($responseText, $params);
  318. }
  319. /**
  320. * Test using raw HTTP POST data
  321. *
  322. */
  323. public function testRawPostData()
  324. {
  325. $data = "Chuck Norris never wet his bed as a child. The bed wet itself out of fear.";
  326. $res = $this->client->setRawData($data, 'text/html')->request('POST');
  327. $this->assertEquals($data, $res->getBody(), 'Response body does not contain the expected data');
  328. }
  329. /**
  330. * Test using raw HTTP PUT data
  331. *
  332. * @group ZF-11030
  333. *
  334. */
  335. public function testRawPutData()
  336. {
  337. $data = "Chuck Norris never wet his bed as a child. The bed wet itself out of fear.";
  338. $this->client->setUri($this->baseuri . 'testRawPutData.php');
  339. $this->client->setRawData($data, 'text/plain');
  340. $this->client->setMethod(Zend_Http_Client::PUT);
  341. $response = $this->client->request();
  342. $this->assertEquals($data, $response->getBody(), 'Response body does not contain the expected data');
  343. }
  344. /**
  345. * Test using raw HTTP DELETE data
  346. *
  347. * @group ZF-11030
  348. *
  349. */
  350. public function testRawDeleteData()
  351. {
  352. $data = "Chuck Norris never wet his bed as a child. The bed wet itself out of fear.";
  353. $this->client->setUri($this->baseuri . 'testRawDeleteData.php');
  354. $this->client->setRawData($data, 'text/plain');
  355. $this->client->setMethod(Zend_Http_Client::DELETE);
  356. $response = $this->client->request();
  357. $this->assertEquals($data, $response->getBody(), 'Response body does not contain the expected data');
  358. }
  359. /**
  360. * Make sure we can reset the parameters between consecutive requests
  361. *
  362. */
  363. public function testResetParameters()
  364. {
  365. $params = array(
  366. 'quest' => 'To seek the holy grail',
  367. 'YourMother' => 'Was a hamster',
  368. 'specialChars' => '<>$+ &?=[]^%',
  369. 'array' => array('firstItem', 'secondItem', '3rdItem')
  370. );
  371. $headers = array("X-Foo" => "bar");
  372. $this->client->setParameterPost($params);
  373. $this->client->setParameterGet($params);
  374. $this->client->setHeaders($headers);
  375. $res = $this->client->request('POST');
  376. $this->assertContains(serialize($params) . "\n" . serialize($params),
  377. $res->getBody(), "returned body does not contain all GET and POST parameters (it should!)");
  378. $this->client->resetParameters();
  379. $res = $this->client->request('POST');
  380. $this->assertNotContains(serialize($params), $res->getBody(),
  381. "returned body contains GET or POST parameters (it shouldn't!)");
  382. $this->assertContains($headers["X-Foo"], $this->client->getHeader("X-Foo"), "Header not preserved by reset");
  383. $this->client->resetParameters(true);
  384. $this->assertNull($this->client->getHeader("X-Foo"), "Header preserved by reset(true)");
  385. }
  386. /**
  387. * Test parameters get reset when we unset them
  388. *
  389. */
  390. public function testParameterUnset()
  391. {
  392. $this->client->setUri($this->baseuri . 'testResetParameters.php');
  393. $gparams = array (
  394. 'cheese' => 'camambert',
  395. 'beer' => 'jever pilnsen',
  396. );
  397. $pparams = array (
  398. 'from' => 'bob',
  399. 'to' => 'alice'
  400. );
  401. $this->client->setParameterGet($gparams)->setParameterPost($pparams);
  402. // Remove some parameters
  403. $this->client->setParameterGet('cheese', null)->setParameterPost('to', null);
  404. $res = $this->client->request('POST');
  405. $this->assertNotContains('cheese', $res->getBody(), 'The "cheese" GET parameter was expected to be unset');
  406. $this->assertNotContains('alice', $res->getBody(), 'The "to" POST parameter was expected to be unset');
  407. }
  408. /**
  409. * Header Tests
  410. */
  411. /**
  412. * Make sure we can set a single header
  413. *
  414. */
  415. public function testHeadersSingle()
  416. {
  417. $this->client->setUri($this->baseuri . 'testHeaders.php');
  418. $headers = array(
  419. 'Accept-encoding' => 'gzip,deflate',
  420. 'X-baz' => 'Foo',
  421. 'X-powered-by' => 'A large wooden badger'
  422. );
  423. foreach ($headers as $key => $val) {
  424. $this->client->setHeaders($key, $val);
  425. }
  426. $acceptHeader = "Accept: text/xml,text/html,*/*";
  427. $this->client->setHeaders($acceptHeader);
  428. $res = $this->client->request('TRACE');
  429. if ($res->getStatus() == 405 || $res->getStatus() == 501) {
  430. $this->markTestSkipped("Server does not allow the TRACE method");
  431. }
  432. $body = strtolower($res->getBody());
  433. foreach ($headers as $key => $val)
  434. $this->assertContains(strtolower("$key: $val"), $body);
  435. $this->assertContains(strtolower($acceptHeader), $body);
  436. }
  437. /**
  438. * Test we can set an array of headers
  439. *
  440. */
  441. public function testHeadersArray()
  442. {
  443. $this->client->setUri($this->baseuri . 'testHeaders.php');
  444. $headers = array(
  445. 'Accept-encoding' => 'gzip,deflate',
  446. 'X-baz' => 'Foo',
  447. 'X-powered-by' => 'A large wooden badger',
  448. 'Accept: text/xml,text/html,*/*'
  449. );
  450. $this->client->setHeaders($headers);
  451. $res = $this->client->request('TRACE');
  452. if ($res->getStatus() == 405 || $res->getStatus() == 501) {
  453. $this->markTestSkipped("Server does not allow the TRACE method");
  454. }
  455. $body = strtolower($res->getBody());
  456. foreach ($headers as $key => $val) {
  457. if (is_string($key)) {
  458. $this->assertContains(strtolower("$key: $val"), $body);
  459. } else {
  460. $this->assertContains(strtolower($val), $body);
  461. }
  462. }
  463. }
  464. /**
  465. * Test we can set a set of values for one header
  466. *
  467. */
  468. public function testMultipleHeader()
  469. {
  470. $this->client->setUri($this->baseuri . 'testHeaders.php');
  471. $headers = array(
  472. 'Accept-encoding' => 'gzip,deflate',
  473. 'X-baz' => 'Foo',
  474. 'X-powered-by' => array(
  475. 'A large wooden badger',
  476. 'My Shiny Metal Ass',
  477. 'Dark Matter'
  478. ),
  479. 'Cookie' => array(
  480. 'foo=bar',
  481. 'baz=waka'
  482. )
  483. );
  484. $this->client->setHeaders($headers);
  485. $res = $this->client->request('TRACE');
  486. if ($res->getStatus() == 405 || $res->getStatus() == 501) {
  487. $this->markTestSkipped("Server does not allow the TRACE method");
  488. }
  489. $body = strtolower($res->getBody());
  490. foreach ($headers as $key => $val) {
  491. if (is_array($val))
  492. $val = implode(', ', $val);
  493. $this->assertContains(strtolower("$key: $val"), $body);
  494. }
  495. }
  496. /**
  497. * Redirection tests
  498. */
  499. /**
  500. * Test the client properly redirects in default mode
  501. *
  502. */
  503. public function testRedirectDefault()
  504. {
  505. $this->client->setUri($this->baseuri . 'testRedirections.php');
  506. // Set some parameters
  507. $this->client->setParameterGet('swallow', 'african');
  508. $this->client->setParameterPost('Camelot', 'A silly place');
  509. // Request
  510. $res = $this->client->request('POST');
  511. $this->assertEquals(3, $this->client->getRedirectionsCount(), 'Redirection counter is not as expected');
  512. // Make sure the body does *not* contain the set parameters
  513. $this->assertNotContains('swallow', $res->getBody());
  514. $this->assertNotContains('Camelot', $res->getBody());
  515. }
  516. /**
  517. * Make sure the client properly redirects in strict mode
  518. *
  519. */
  520. public function testRedirectStrict()
  521. {
  522. $this->client->setUri($this->baseuri . 'testRedirections.php');
  523. // Set some parameters
  524. $this->client->setParameterGet('swallow', 'african');
  525. $this->client->setParameterPost('Camelot', 'A silly place');
  526. // Set strict redirections
  527. $this->client->setConfig(array('strictredirects' => true));
  528. // Request
  529. $res = $this->client->request('POST');
  530. $this->assertEquals(3, $this->client->getRedirectionsCount(), 'Redirection counter is not as expected');
  531. // Make sure the body *does* contain the set parameters
  532. $this->assertContains('swallow', $res->getBody());
  533. $this->assertContains('Camelot', $res->getBody());
  534. }
  535. /**
  536. * Make sure redirections stop when limit is exceeded
  537. *
  538. */
  539. public function testMaxRedirectsExceeded()
  540. {
  541. $this->client->setUri($this->baseuri . 'testRedirections.php');
  542. // Set some parameters
  543. $this->client->setParameterGet('swallow', 'african');
  544. $this->client->setParameterPost('Camelot', 'A silly place');
  545. // Set lower max redirections
  546. // Try with strict redirections first
  547. $this->client->setConfig(array('strictredirects' => true, 'maxredirects' => 2));
  548. $res = $this->client->request('POST');
  549. $this->assertTrue($res->isRedirect(),
  550. "Last response was not a redirection as expected. Response code: {$res->getStatus()}. Redirections counter: {$this->client->getRedirectionsCount()} (when strict redirects are on)");
  551. // Then try with normal redirections
  552. $this->client->setParameterGet('redirection', '0');
  553. $this->client->setConfig(array('strictredirects' => false));
  554. $res = $this->client->request('POST');
  555. $this->assertTrue($res->isRedirect(),
  556. "Last response was not a redirection as expected. Response code: {$res->getStatus()}. Redirections counter: {$this->client->getRedirectionsCount()} (when strict redirects are off)");
  557. }
  558. /**
  559. * Test we can properly redirect to an absolute path (not full URI)
  560. *
  561. */
  562. public function testAbsolutePathRedirect()
  563. {
  564. $this->client->setUri($this->baseuri . 'testRelativeRedirections.php');
  565. $this->client->setParameterGet('redirect', 'abpath');
  566. $this->client->setConfig(array('maxredirects' => 1));
  567. // Get the host and port part of our baseuri
  568. $uri = $this->client->getUri()->getScheme() . '://' . $this->client->getUri()->getHost() . ':' .
  569. $this->client->getUri()->getPort();
  570. $res = $this->client->request('GET');
  571. $this->assertEquals("{$uri}/path/to/fake/file.ext?redirect=abpath", $this->client->getUri(true),
  572. "The new location is not as expected: {$this->client->getUri(true)}");
  573. }
  574. /**
  575. * Test we can properly redirect to a relative path
  576. *
  577. */
  578. public function testRelativePathRedirect()
  579. {
  580. $this->client->setUri($this->baseuri . 'testRelativeRedirections.php');
  581. $this->client->setParameterGet('redirect', 'relpath');
  582. $this->client->setConfig(array('maxredirects' => 1));
  583. // Set the new expected URI
  584. $uri = clone $this->client->getUri();
  585. $uri->setPath(rtrim(dirname($uri->getPath()), '/') . '/path/to/fake/file.ext');
  586. $uri = $uri->__toString();
  587. $res = $this->client->request('GET');
  588. $this->assertEquals("{$uri}?redirect=relpath", $this->client->getUri(true),
  589. "The new location is not as expected: {$this->client->getUri(true)}");
  590. }
  591. /**
  592. * HTTP Authentication Tests
  593. *
  594. */
  595. /**
  596. * Test we can properly use Basic HTTP authentication
  597. *
  598. */
  599. public function testHttpAuthBasic()
  600. {
  601. $this->client->setUri($this->baseuri. 'testHttpAuth.php');
  602. $this->client->setParameterGet(array(
  603. 'user' => 'alice',
  604. 'pass' => 'secret',
  605. 'method' => 'Basic'
  606. ));
  607. // First - fail password
  608. $this->client->setAuth('alice', 'wrong');
  609. $res = $this->client->request();
  610. $this->assertEquals(401, $res->getStatus(), 'Expected HTTP 401 response was not recieved');
  611. // Now use good password
  612. $this->client->setAuth('alice', 'secret');
  613. $res = $this->client->request();
  614. $this->assertEquals(200, $res->getStatus(), 'Expected HTTP 200 response was not recieved');
  615. }
  616. /**
  617. * Test that we can properly use Basic HTTP authentication by specifying username and password
  618. * in the URI
  619. *
  620. */
  621. public function testHttpAuthBasicWithCredentialsInUri()
  622. {
  623. $uri = str_replace('http://', 'http://%s:%s@', $this->baseuri) . 'testHttpAuth.php';
  624. $this->client->setParameterGet(array(
  625. 'user' => 'alice',
  626. 'pass' => 'secret',
  627. 'method' => 'Basic'
  628. ));
  629. // First - fail password
  630. $this->client->setUri(sprintf($uri, 'alice', 'wrong'));
  631. $res = $this->client->request();
  632. $this->assertEquals(401, $res->getStatus(), 'Expected HTTP 401 response was not recieved');
  633. // Now use good password
  634. $this->client->setUri(sprintf($uri, 'alice', 'secret'));
  635. $res = $this->client->request();
  636. $this->assertEquals(200, $res->getStatus(), 'Expected HTTP 200 response was not recieved');
  637. }
  638. /**
  639. * Test we can unset HTTP authentication
  640. *
  641. */
  642. public function testCancelAuth()
  643. {
  644. $this->client->setUri($this->baseuri. 'testHttpAuth.php');
  645. // Set auth and cancel it
  646. $this->client->setAuth('alice', 'secret');
  647. $this->client->setAuth(false);
  648. $res = $this->client->request();
  649. $this->assertEquals(401, $res->getStatus(), 'Expected HTTP 401 response was not recieved');
  650. $this->assertNotContains('alice', $res->getBody(), "Body contains the user name, but it shouldn't");
  651. $this->assertNotContains('secret', $res->getBody(), "Body contains the password, but it shouldn't");
  652. }
  653. /**
  654. * Test that we can unset HTTP authentication when credentials is specified in the URI
  655. *
  656. */
  657. public function testCancelAuthWithCredentialsInUri()
  658. {
  659. $uri = str_replace('http://', 'http://%s:%s@', $this->baseuri) . 'testHttpAuth.php';
  660. // Set auth and cancel it
  661. $this->client->setUri(sprintf($uri, 'alice', 'secret'));
  662. $this->client->setAuth(false);
  663. $res = $this->client->request();
  664. $this->assertEquals(401, $res->getStatus(), 'Expected HTTP 401 response was not recieved');
  665. $this->assertNotContains('alice', $res->getBody(), "Body contains the user name, but it shouldn't");
  666. $this->assertNotContains('secret', $res->getBody(), "Body contains the password, but it shouldn't");
  667. }
  668. /**
  669. * Cookie and CookieJar Tests
  670. *
  671. */
  672. /**
  673. * Test we can set string cookies with no jar
  674. *
  675. */
  676. public function testCookiesStringNoJar()
  677. {
  678. $this->client->setUri($this->baseuri. 'testCookies.php');
  679. $cookies = array(
  680. 'name' => 'value',
  681. 'cookie' => 'crumble'
  682. );
  683. foreach ($cookies as $k => $v) {
  684. $this->client->setCookie($k, $v);
  685. }
  686. $res = $this->client->request();
  687. $this->assertEquals($res->getBody(), serialize($cookies), 'Response body does not contain the expected cookies');
  688. }
  689. /**
  690. * Make sure we can set object cookies with no jar
  691. *
  692. */
  693. public function testSetCookieObjectNoJar()
  694. {
  695. $this->client->setUri($this->baseuri. 'testCookies.php');
  696. $refuri = $this->client->getUri();
  697. $cookies = array(
  698. Zend_Http_Cookie::fromString('chocolate=chips', $refuri),
  699. Zend_Http_Cookie::fromString('crumble=apple', $refuri)
  700. );
  701. $strcookies = array();
  702. foreach ($cookies as $c) {
  703. $this->client->setCookie($c);
  704. $strcookies[$c->getName()] = $c->getValue();
  705. }
  706. $res = $this->client->request();
  707. $this->assertEquals($res->getBody(), serialize($strcookies), 'Response body does not contain the expected cookies');
  708. }
  709. /**
  710. * Make sure we can set an array of object cookies
  711. *
  712. */
  713. public function testSetCookieObjectArray()
  714. {
  715. $this->client->setUri($this->baseuri. 'testCookies.php');
  716. $refuri = $this->client->getUri();
  717. $cookies = array(
  718. Zend_Http_Cookie::fromString('chocolate=chips', $refuri),
  719. Zend_Http_Cookie::fromString('crumble=apple', $refuri),
  720. Zend_Http_Cookie::fromString('another=cookie', $refuri)
  721. );
  722. $this->client->setCookie($cookies);
  723. $strcookies = array();
  724. foreach ($cookies as $c) {
  725. $strcookies[$c->getName()] = $c->getValue();
  726. }
  727. $res = $this->client->request();
  728. $this->assertEquals($res->getBody(), serialize($strcookies), 'Response body does not contain the expected cookies');
  729. }
  730. /**
  731. * Make sure we can set an array of string cookies
  732. *
  733. */
  734. public function testSetCookieStringArray()
  735. {
  736. $this->client->setUri($this->baseuri. 'testCookies.php');
  737. $cookies = array(
  738. 'chocolate' => 'chips',
  739. 'crumble' => 'apple',
  740. 'another' => 'cookie'
  741. );
  742. $this->client->setCookie($cookies);
  743. $res = $this->client->request();
  744. $this->assertEquals($res->getBody(), serialize($cookies), 'Response body does not contain the expected cookies');
  745. }
  746. /**
  747. * Make sure we can set cookie objects with a jar
  748. *
  749. */
  750. public function testSetCookieObjectJar()
  751. {
  752. $this->client->setUri($this->baseuri. 'testCookies.php');
  753. $this->client->setCookieJar();
  754. $refuri = $this->client->getUri();
  755. $cookies = array(
  756. Zend_Http_Cookie::fromString('chocolate=chips', $refuri),
  757. Zend_Http_Cookie::fromString('crumble=apple', $refuri)
  758. );
  759. $strcookies = array();
  760. foreach ($cookies as $c) {
  761. $this->client->setCookie($c);
  762. $strcookies[$c->getName()] = $c->getValue();
  763. }
  764. $res = $this->client->request();
  765. $this->assertEquals($res->getBody(), serialize($strcookies), 'Response body does not contain the expected cookies');
  766. }
  767. /**
  768. * File Upload Tests
  769. *
  770. */
  771. /**
  772. * Test we can upload raw data as a file
  773. *
  774. */
  775. public function testUploadRawData()
  776. {
  777. if (!ini_get('file_uploads')) {
  778. $this->markTestSkipped('File uploads disabled.');
  779. }
  780. $this->client->setUri($this->baseuri. 'testUploads.php');
  781. $rawdata = file_get_contents(__FILE__);
  782. $this->client->setFileUpload('myfile.txt', 'uploadfile', $rawdata, 'text/plain');
  783. $res = $this->client->request('POST');
  784. $body = 'uploadfile myfile.txt text/plain ' . strlen($rawdata) . "\n";
  785. $this->assertEquals($body, $res->getBody(), 'Response body does not include expected upload parameters');
  786. }
  787. /**
  788. * Test we can upload an existing file
  789. *
  790. */
  791. public function testUploadLocalFile()
  792. {
  793. if (!ini_get('file_uploads')) {
  794. $this->markTestSkipped('File uploads disabled.');
  795. }
  796. $this->client->setUri($this->baseuri. 'testUploads.php');
  797. $this->client->setFileUpload(__FILE__, 'uploadfile', null, 'text/x-foo-bar');
  798. $res = $this->client->request('POST');
  799. $size = filesize(__FILE__);
  800. $body = "uploadfile " . basename(__FILE__) . " text/x-foo-bar $size\n";
  801. $this->assertEquals($body, $res->getBody(), 'Response body does not include expected upload parameters');
  802. }
  803. public function testUploadLocalDetectMime()
  804. {
  805. if (!ini_get('file_uploads')) {
  806. $this->markTestSkipped('File uploads disabled.');
  807. }
  808. $detect = null;
  809. if (function_exists('finfo_file')) {
  810. $f = @finfo_open(FILEINFO_MIME);
  811. if ($f) $detect = 'finfo';
  812. } elseif (function_exists('mime_content_type')) {
  813. if (mime_content_type(__FILE__)) {
  814. $detect = 'mime_magic';
  815. }
  816. }
  817. if (! $detect) {
  818. $this->markTestSkipped('No MIME type detection capability (fileinfo or mime_magic extensions) is available');
  819. }
  820. $file = dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'staticFile.jpg';
  821. $this->client->setUri($this->baseuri. 'testUploads.php');
  822. $this->client->setFileUpload($file, 'uploadfile');
  823. $res = $this->client->request('POST');
  824. $size = filesize($file);
  825. $body = "uploadfile " . basename($file) . " image/jpeg $size\n";
  826. $this->assertEquals($body, $res->getBody(), 'Response body does not include expected upload parameters (detect: ' . $detect . ')');
  827. }
  828. public function testUploadNameWithSpecialChars()
  829. {
  830. if (!ini_get('file_uploads')) {
  831. $this->markTestSkipped('File uploads disabled.');
  832. }
  833. $this->client->setUri($this->baseuri. 'testUploads.php');
  834. $rawdata = file_get_contents(__FILE__);
  835. $this->client->setFileUpload('/some strage/path%/with[!@#$&]/myfile.txt', 'uploadfile', $rawdata, 'text/plain');
  836. $res = $this->client->request('POST');
  837. $body = 'uploadfile myfile.txt text/plain ' . strlen($rawdata) . "\n";
  838. $this->assertEquals($body, $res->getBody(), 'Response body does not include expected upload parameters');
  839. }
  840. public function testStaticLargeFileDownload()
  841. {
  842. $this->client->setUri($this->baseuri . 'staticFile.jpg');
  843. $got = $this->client->request()->getBody();
  844. $expected = $this->_getTestFileContents('staticFile.jpg');
  845. $this->assertEquals($expected, $got, 'Downloaded file does not seem to match!');
  846. }
  847. /**
  848. * Test that one can upload multiple files with the same form name, as an
  849. * array
  850. *
  851. * @link http://framework.zend.com/issues/browse/ZF-5744
  852. */
  853. public function testMutipleFilesWithSameFormNameZF5744()
  854. {
  855. if (!ini_get('file_uploads')) {
  856. $this->markTestSkipped('File uploads disabled.');
  857. }
  858. $rawData = 'Some test raw data here...';
  859. $this->client->setUri($this->baseuri . 'testUploads.php');
  860. $files = array('file1.txt', 'file2.txt', 'someotherfile.foo');
  861. $expectedBody = '';
  862. foreach($files as $filename) {
  863. $this->client->setFileUpload($filename, 'uploadfile[]', $rawData, 'text/plain');
  864. $expectedBody .= "uploadfile $filename text/plain " . strlen($rawData) . "\n";
  865. }
  866. $res = $this->client->request('POST');
  867. $this->assertEquals($expectedBody, $res->getBody(), 'Response body does not include expected upload parameters');
  868. }
  869. /**
  870. * Test that lines that might be evaluated as boolean false do not break
  871. * the reading prematurely.
  872. *
  873. * @link http://framework.zend.com/issues/browse/ZF-4238
  874. */
  875. public function testZF4238FalseLinesInResponse()
  876. {
  877. $this->client->setUri($this->baseuri . 'ZF4238-zerolineresponse.txt');
  878. $got = $this->client->request()->getBody();
  879. $expected = $this->_getTestFileContents('ZF4238-zerolineresponse.txt');
  880. $this->assertEquals($expected, $got);
  881. }
  882. public function testStreamResponse()
  883. {
  884. if(!($this->client->getAdapter() instanceof Zend_Http_Client_Adapter_Stream)) {
  885. $this->markTestSkipped('Current adapter does not support streaming');
  886. return;
  887. }
  888. $this->client->setUri($this->baseuri . 'staticFile.jpg');
  889. $this->client->setStream();
  890. $response = $this->client->request();
  891. $this->assertTrue($response instanceof Zend_Http_Response_Stream, 'Request did not return stream response!');
  892. $this->assertTrue(is_resource($response->getStream()), 'Request does not contain stream!');
  893. $stream_name = $response->getStreamName();
  894. $stream_read = stream_get_contents($response->getStream());
  895. $file_read = file_get_contents($stream_name);
  896. $expected = $this->_getTestFileContents('staticFile.jpg');
  897. $this->assertEquals($expected, $stream_read, 'Downloaded stream does not seem to match!');
  898. $this->assertEquals($expected, $file_read, 'Downloaded file does not seem to match!');
  899. }
  900. public function testStreamResponseBody()
  901. {
  902. if(!($this->client->getAdapter() instanceof Zend_Http_Client_Adapter_Stream)) {
  903. $this->markTestSkipped('Current adapter does not support streaming');
  904. return;
  905. }
  906. $this->client->setUri($this->baseuri . 'staticFile.jpg');
  907. $this->client->setStream();
  908. $response = $this->client->request();
  909. $this->assertTrue($response instanceof Zend_Http_Response_Stream, 'Request did not return stream response!');
  910. $this->assertTrue(is_resource($response->getStream()), 'Request does not contain stream!');
  911. $body = $response->getBody();
  912. $expected = $this->_getTestFileContents('staticFile.jpg');
  913. $this->assertEquals($expected, $body, 'Downloaded stream does not seem to match!');
  914. }
  915. public function testStreamResponseNamed()
  916. {
  917. if(!($this->client->getAdapter() instanceof Zend_Http_Client_Adapter_Stream)) {
  918. $this->markTestSkipped('Current adapter does not support streaming');
  919. return;
  920. }
  921. $this->client->setUri($this->baseuri . 'staticFile.jpg');
  922. $outfile = tempnam(sys_get_temp_dir(), "outstream");
  923. $this->client->setStream($outfile);
  924. $response = $this->client->request();
  925. $this->assertTrue($response instanceof Zend_Http_Response_Stream, 'Request did not return stream response!');
  926. $this->assertTrue(is_resource($response->getStream()), 'Request does not contain stream!');
  927. $this->assertEquals($outfile, $response->getStreamName());
  928. $stream_read = stream_get_contents($response->getStream());
  929. $file_read = file_get_contents($outfile);
  930. $expected = $this->_getTestFileContents('staticFile.jpg');
  931. $this->assertEquals($expected, $stream_read, 'Downloaded stream does not seem to match!');
  932. $this->assertEquals($expected, $file_read, 'Downloaded file does not seem to match!');
  933. }
  934. public function testStreamRequest()
  935. {
  936. if(!($this->client->getAdapter() instanceof Zend_Http_Client_Adapter_Stream)) {
  937. $this->markTestSkipped('Current adapter does not support streaming');
  938. return;
  939. }
  940. $data = fopen(dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'staticFile.jpg', "r");
  941. $res = $this->client->setRawData($data, 'image/jpeg')->request('PUT');
  942. $expected = $this->_getTestFileContents('staticFile.jpg');
  943. $this->assertEquals($expected, $res->getBody(), 'Response body does not contain the expected data');
  944. }
  945. /**
  946. * Test that we can deal with double Content-Length headers
  947. *
  948. * @link http://framework.zend.com/issues/browse/ZF-9404
  949. */
  950. public function testZF9404DoubleContentLengthHeader()
  951. {
  952. $this->client->setUri($this->baseuri . 'ZF9404-doubleContentLength.php');
  953. $expect = filesize(dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'ZF9404-doubleContentLength.php');
  954. $response = $this->client->request();
  955. if (! $response->isSuccessful()) {
  956. throw new ErrorException("Error requesting test URL");
  957. }
  958. $clen = $response->getHeader('content-length');
  959. if (! (is_array($clen))) {
  960. $this->markTestSkipped("Didn't get multiple Content-length headers");
  961. }
  962. $this->assertEquals($expect, strlen($response->getBody()));
  963. }
  964. /**
  965. * @group ZF-10645
  966. */
  967. public function testPutRequestsHonorSpecifiedContentType()
  968. {
  969. $this->client->setUri($this->baseuri . 'ZF10645-PutContentType.php');
  970. $this->client->setMethod(Zend_Http_Client::PUT);
  971. $data = array('foo' => 'bar');
  972. $this->client->setRawData(http_build_query($data), 'text/html; charset=ISO-8859-1');
  973. $response = $this->client->request();
  974. $request = $this->client->getLastRequest();
  975. $this->assertContains('text/html; charset=ISO-8859-1', $request, $request);
  976. $this->assertContains('REQUEST_METHOD: PUT', $response->getBody(), $response->getBody());
  977. }
  978. /**
  979. * @group ZF-11418
  980. */
  981. public function testMultiplePuts()
  982. {
  983. $this->client->setUri($this->baseuri . 'ZF10645-PutContentType.php');
  984. $data= 'test';
  985. $this->client->setRawData($data, 'text/plain');
  986. $this->client->setMethod(Zend_Http_Client::PUT);
  987. $response = $this->client->request();
  988. $this->assertContains('REQUEST_METHOD: PUT', $response->getBody(), $response->getBody());
  989. $this->client->resetParameters(true);
  990. $this->client->setUri($this->baseuri . 'ZF10645-PutContentType.php');
  991. $this->client->setMethod(Zend_Http_Client::PUT);
  992. $response = $this->client->request();
  993. $request= $this->client->getLastRequest();
  994. $this->assertNotContains('Content-Type: text/plain', $request);
  995. }
  996. /**
  997. * @group ZF-11598
  998. */
  999. public function testGetAdapterWithoutSet()
  1000. {
  1001. $client = new Zend_Http_Client(null, $this->config);
  1002. $adapter = $client->getAdapter();
  1003. $this->assertTrue(!empty($adapter));
  1004. }
  1005. /**
  1006. * Internal helpder function to get the contents of test files
  1007. *
  1008. * @param string $file
  1009. * @return string
  1010. */
  1011. protected function _getTestFileContents($file)
  1012. {
  1013. return file_get_contents(dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR .
  1014. '_files' . DIRECTORY_SEPARATOR . $file);
  1015. }
  1016. /**
  1017. * Data provider for complex, nesting parameter arrays
  1018. *
  1019. * @return array
  1020. */
  1021. static public function parameterArrayProvider()
  1022. {
  1023. return array(
  1024. array(
  1025. array(
  1026. 'quest' => 'To seek the holy grail',
  1027. 'YourMother' => 'Was a hamster',
  1028. 'specialChars' => '<>$+ &?=[]^%',
  1029. 'array' => array('firstItem', 'secondItem', '3rdItem')
  1030. )
  1031. ),
  1032. array(
  1033. array(
  1034. 'someData' => array(
  1035. "1",
  1036. "2",
  1037. 'key' => 'value',
  1038. 'nesting' => array(
  1039. 'a' => 'AAA',
  1040. 'b' => 'BBB'
  1041. )
  1042. ),
  1043. 'someOtherData' => array('foo', 'bar')
  1044. )
  1045. ),
  1046. array(
  1047. array(
  1048. 'foo1' => 'bar',
  1049. 'foo2' => array('baz', 'w00t')
  1050. )
  1051. )
  1052. );
  1053. }
  1054. /**
  1055. * Data provider for invalid configuration containers
  1056. *
  1057. * @return array
  1058. */
  1059. static public function invalidConfigProvider()
  1060. {
  1061. return array(
  1062. array(false),
  1063. array('foo => bar'),
  1064. array(null),
  1065. array(new stdClass),
  1066. array(55)
  1067. );
  1068. }
  1069. }