CommonHttpTests.php 36 KB

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