CommonHttpTests.php 35 KB

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