CommonHttpTests.php 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  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-2011 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-2011 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. * Internal helpder function to get the contents of test files
  998. *
  999. * @param string $file
  1000. * @return string
  1001. */
  1002. protected function _getTestFileContents($file)
  1003. {
  1004. return file_get_contents(dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR .
  1005. '_files' . DIRECTORY_SEPARATOR . $file);
  1006. }
  1007. /**
  1008. * Data provider for complex, nesting parameter arrays
  1009. *
  1010. * @return array
  1011. */
  1012. static public function parameterArrayProvider()
  1013. {
  1014. return array(
  1015. array(
  1016. array(
  1017. 'quest' => 'To seek the holy grail',
  1018. 'YourMother' => 'Was a hamster',
  1019. 'specialChars' => '<>$+ &?=[]^%',
  1020. 'array' => array('firstItem', 'secondItem', '3rdItem')
  1021. )
  1022. ),
  1023. array(
  1024. array(
  1025. 'someData' => array(
  1026. "1",
  1027. "2",
  1028. 'key' => 'value',
  1029. 'nesting' => array(
  1030. 'a' => 'AAA',
  1031. 'b' => 'BBB'
  1032. )
  1033. ),
  1034. 'someOtherData' => array('foo', 'bar')
  1035. )
  1036. ),
  1037. array(
  1038. array(
  1039. 'foo1' => 'bar',
  1040. 'foo2' => array('baz', 'w00t')
  1041. )
  1042. )
  1043. );
  1044. }
  1045. /**
  1046. * Data provider for invalid configuration containers
  1047. *
  1048. * @return array
  1049. */
  1050. static public function invalidConfigProvider()
  1051. {
  1052. return array(
  1053. array(false),
  1054. array('foo => bar'),
  1055. array(null),
  1056. array(new stdClass),
  1057. array(55)
  1058. );
  1059. }
  1060. }