SocketTest.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. <?php
  2. // Read local configuration
  3. if (! defined('TESTS_ZEND_HTTP_CLIENT_BASEURI') &&
  4. is_readable('TestConfiguration.php')) {
  5. require_once 'TestConfiguration.php';
  6. }
  7. require_once realpath(dirname(__FILE__) . '/../../../') . '/TestHelper.php';
  8. require_once 'Zend/Http/Client.php';
  9. require_once 'PHPUnit/Framework/TestCase.php';
  10. require_once 'Zend/Uri/Http.php';
  11. /**
  12. * This Testsuite includes all Zend_Http_Client that require a working web
  13. * server to perform. It was designed to be extendable, so that several
  14. * test suites could be run against several servers, with different client
  15. * adapters and configurations.
  16. *
  17. * Note that $this->baseuri must point to a directory on a web server
  18. * containing all the files under the _files directory. You should symlink
  19. * or copy these files and set 'baseuri' properly.
  20. *
  21. * You can also set the proper constant in your test configuration file to
  22. * point to the right place.
  23. *
  24. * @category Zend
  25. * @package Zend_Http_Client
  26. * @subpackage UnitTests
  27. * @version $Id$
  28. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  29. * @license http://framework.zend.com/license/new-bsd New BSD License
  30. */
  31. class Zend_Http_Client_SocketTest extends PHPUnit_Framework_TestCase
  32. {
  33. /**
  34. * The bast URI for this test, containing all files in the _files directory
  35. * Should be set in TestConfiguration.php or TestConfiguration.php.dist
  36. *
  37. * @var string
  38. */
  39. protected $baseuri;
  40. /**
  41. * Common HTTP client
  42. *
  43. * @var Zend_Http_Client
  44. */
  45. protected $client = null;
  46. /**
  47. * Configuration array
  48. *
  49. * @var array
  50. */
  51. protected $config = array(
  52. 'adapter' => 'Zend_Http_Client_Adapter_Socket'
  53. );
  54. /**
  55. * Set up the test case
  56. *
  57. */
  58. protected function setUp()
  59. {
  60. if (defined('TESTS_ZEND_HTTP_CLIENT_BASEURI') &&
  61. Zend_Uri_Http::check(TESTS_ZEND_HTTP_CLIENT_BASEURI)) {
  62. $this->baseuri = TESTS_ZEND_HTTP_CLIENT_BASEURI;
  63. if (substr($this->baseuri, -1) != '/') $this->baseuri .= '/';
  64. $uri = $this->baseuri . $this->getName() . '.php';
  65. $this->client = new Zend_Http_Client($uri, $this->config);
  66. } else {
  67. // Skip tests
  68. $this->markTestSkipped("Zend_Http_Client dynamic tests are not enabled in TestConfiguration.php");
  69. }
  70. }
  71. /**
  72. * Simple request tests
  73. */
  74. /**
  75. * Test simple requests
  76. *
  77. */
  78. public function testSimpleRequests()
  79. {
  80. $methods = array('GET', 'POST', 'OPTIONS', 'PUT', 'DELETE');
  81. foreach ($methods as $method) {
  82. $res = $this->client->request($method);
  83. $this->assertEquals('Success', $res->getBody(), "HTTP {$method} request failed.");
  84. }
  85. }
  86. /**
  87. * Test we can get the last request as string
  88. *
  89. */
  90. public function testGetLastRequest()
  91. {
  92. $this->client->setUri($this->baseuri . 'testHeaders.php');
  93. $this->client->setParameterGet('someinput', 'somevalue');
  94. $this->client->setHeaders(array(
  95. 'X-Powered-By' => 'My Glorious Golden Ass',
  96. ));
  97. $res = $this->client->request(Zend_Http_Client::TRACE);
  98. if ($res->getStatus() == 405) {
  99. $this->markTestSkipped("Server does not allow the TRACE method");
  100. }
  101. $this->assertEquals($this->client->getLastRequest(), $res->getBody(), 'Response body should be exactly like the last request');
  102. }
  103. /**
  104. * Test the getLastResponse() method actually returns the last response
  105. *
  106. */
  107. public function testGetLastResponse()
  108. {
  109. // First, make sure we get null before the request
  110. $this->assertEquals(null, $this->client->getLastResponse(), 'getLastResponse() is still expected to return null');
  111. // Now, test we get a proper response after the request
  112. $this->client->setUri($this->baseuri . 'testHeaders.php');
  113. $response = $this->client->request();
  114. $this->assertTrue(($response === $this->client->getLastResponse()), 'Response is expected to be identical to the result of getLastResponse()');
  115. }
  116. /**
  117. * Test that getLastResponse returns null when not storing
  118. *
  119. */
  120. public function testGetLastResponseWhenNotStoring()
  121. {
  122. $this->client->setUri($this->baseuri . 'testHeaders.php');
  123. $this->client->setConfig(array('storeresponse' => false));
  124. $response = $this->client->request();
  125. $this->assertEquals(null, $this->client->getLastResponse(), 'getLastResponse is expected to be null when not storing');
  126. }
  127. /**
  128. * GET and POST parameters tests
  129. */
  130. /**
  131. * Test we can properly send GET parameters
  132. *
  133. */
  134. public function testGetData()
  135. {
  136. $params = array(
  137. 'quest' => 'To seek the holy grail',
  138. 'YourMother' => 'Was a hamster',
  139. 'specialChars' => '<>$+ &?=[]^%',
  140. 'array' => array('firstItem', 'secondItem', '3rdItem')
  141. );
  142. $this->client->setUri($this->client->getUri(true) . '?name=Arthur');
  143. $this->client->setParameterGet($params);
  144. $res = $this->client->request('GET');
  145. $this->assertEquals(serialize(array_merge(array('name' => 'Arthur'), $params)), $res->getBody());
  146. }
  147. /**
  148. * Test that setting the same parameter twice in the query string does not
  149. * get reduced to a single value only.
  150. *
  151. */
  152. public function testDoubleGetParameter()
  153. {
  154. $qstr = 'foo=bar&foo=baz';
  155. $this->client->setUri($this->baseuri . 'testGetData.php?' . $qstr);
  156. $res = $this->client->request('GET');
  157. $this->assertContains($qstr, $this->client->getLastRequest(), 'Request is expected to contain the entire query string');
  158. }
  159. /**
  160. * Test we can properly send POST parameters with
  161. * application/x-www-form-urlencoded content type
  162. *
  163. */
  164. public function testPostDataUrlEncoded()
  165. {
  166. $this->client->setUri($this->baseuri . 'testPostData.php');
  167. $params = array(
  168. 'quest' => 'To seek the holy grail',
  169. 'YourMother' => 'Was a hamster',
  170. 'specialChars' => '<>$+ &?=[]^%',
  171. 'array' => array('firstItem', 'secondItem', '3rdItem')
  172. );
  173. $this->client->setEncType(Zend_Http_Client::ENC_URLENCODED);
  174. $this->client->setParameterPost($params);
  175. $res = $this->client->request('POST');
  176. $this->assertEquals(serialize($params), $res->getBody(), "POST data integrity test failed");
  177. }
  178. /**
  179. * Test we can properly send POST parameters with
  180. * multipart/form-data content type
  181. *
  182. */
  183. public function testPostDataMultipart()
  184. {
  185. $this->client->setUri($this->baseuri . 'testPostData.php');
  186. $params = array(
  187. 'quest' => 'To seek the holy grail',
  188. 'YourMother' => 'Was a hamster',
  189. 'specialChars' => '<>$+ &?=[]^%',
  190. 'array' => array('firstItem', 'secondItem', '3rdItem')
  191. );
  192. $this->client->setEncType(Zend_Http_Client::ENC_FORMDATA);
  193. $this->client->setParameterPost($params);
  194. $res = $this->client->request('POST');
  195. $this->assertEquals(serialize($params), $res->getBody(), "POST data integrity test failed");
  196. }
  197. /**
  198. * Test using raw HTTP POST data
  199. *
  200. */
  201. public function testRawPostData()
  202. {
  203. $data = "Chuck Norris never wet his bed as a child. The bed wet itself out of fear.";
  204. $res = $this->client->setRawData($data, 'text/html')->request('POST');
  205. $this->assertEquals($data, $res->getBody(), 'Response body does not contain the expected data');
  206. }
  207. /**
  208. * Make sure we can reset the parameters between consecutive requests
  209. *
  210. */
  211. public function testResetParameters()
  212. {
  213. $params = array(
  214. 'quest' => 'To seek the holy grail',
  215. 'YourMother' => 'Was a hamster',
  216. 'specialChars' => '<>$+ &?=[]^%',
  217. 'array' => array('firstItem', 'secondItem', '3rdItem')
  218. );
  219. $this->client->setParameterPost($params);
  220. $this->client->setParameterGet($params);
  221. $res = $this->client->request('POST');
  222. $this->assertContains(serialize($params) . "\n" . serialize($params),
  223. $res->getBody(), "returned body does not contain all GET and POST parameters (it should!)");
  224. $this->client->resetParameters();
  225. $res = $this->client->request('POST');
  226. $this->assertNotContains(serialize($params), $res->getBody(),
  227. "returned body contains GET or POST parameters (it shouldn't!)");
  228. }
  229. /**
  230. * Test parameters get reset when we unset them
  231. *
  232. */
  233. public function testParameterUnset()
  234. {
  235. $this->client->setUri($this->baseuri . 'testResetParameters.php');
  236. $gparams = array (
  237. 'cheese' => 'camambert',
  238. 'beer' => 'jever pilnsen',
  239. );
  240. $pparams = array (
  241. 'from' => 'bob',
  242. 'to' => 'alice'
  243. );
  244. $this->client->setParameterGet($gparams)->setParameterPost($pparams);
  245. // Remove some parameters
  246. $this->client->setParameterGet('cheese', null)->setParameterPost('to', null);
  247. $res = $this->client->request('POST');
  248. $this->assertNotContains('cheese', $res->getBody(), 'The "cheese" GET parameter was expected to be unset');
  249. $this->assertNotContains('alice', $res->getBody(), 'The "to" POST parameter was expected to be unset');
  250. }
  251. /**
  252. * Header Tests
  253. */
  254. /**
  255. * Make sure we can set a single header
  256. *
  257. */
  258. public function testHeadersSingle()
  259. {
  260. $this->client->setUri($this->baseuri . 'testHeaders.php');
  261. $headers = array(
  262. 'Accept-encoding' => 'gzip,deflate',
  263. 'X-baz' => 'Foo',
  264. 'X-powered-by' => 'A large wooden badger'
  265. );
  266. foreach ($headers as $key => $val) {
  267. $this->client->setHeaders($key, $val);
  268. }
  269. $acceptHeader = "Accept: text/xml,text/html,*/*";
  270. $this->client->setHeaders($acceptHeader);
  271. $res = $this->client->request('TRACE');
  272. if ($res->getStatus() == 405) {
  273. $this->markTestSkipped("Server does not allow the TRACE method");
  274. }
  275. $body = strtolower($res->getBody());
  276. foreach ($headers as $key => $val)
  277. $this->assertContains(strtolower("$key: $val"), $body);
  278. $this->assertContains(strtolower($acceptHeader), $body);
  279. }
  280. /**
  281. * Test we can set an array of headers
  282. *
  283. */
  284. public function testHeadersArray()
  285. {
  286. $this->client->setUri($this->baseuri . 'testHeaders.php');
  287. $headers = array(
  288. 'Accept-encoding' => 'gzip,deflate',
  289. 'X-baz' => 'Foo',
  290. 'X-powered-by' => 'A large wooden badger',
  291. 'Accept: text/xml,text/html,*/*'
  292. );
  293. $this->client->setHeaders($headers);
  294. $res = $this->client->request('TRACE');
  295. if ($res->getStatus() == 405) {
  296. $this->markTestSkipped("Server does not allow the TRACE method");
  297. }
  298. $body = strtolower($res->getBody());
  299. foreach ($headers as $key => $val) {
  300. if (is_string($key)) {
  301. $this->assertContains(strtolower("$key: $val"), $body);
  302. } else {
  303. $this->assertContains(strtolower($val), $body);
  304. }
  305. }
  306. }
  307. /**
  308. * Test we can set a set of values for one header
  309. *
  310. */
  311. public function testMultipleHeader()
  312. {
  313. $this->client->setUri($this->baseuri . 'testHeaders.php');
  314. $headers = array(
  315. 'Accept-encoding' => 'gzip,deflate',
  316. 'X-baz' => 'Foo',
  317. 'X-powered-by' => array(
  318. 'A large wooden badger',
  319. 'My Shiny Metal Ass',
  320. 'Dark Matter'
  321. ),
  322. 'Cookie' => array(
  323. 'foo=bar',
  324. 'baz=waka'
  325. )
  326. );
  327. $this->client->setHeaders($headers);
  328. $res = $this->client->request('TRACE');
  329. if ($res->getStatus() == 405) {
  330. $this->markTestSkipped("Server does not allow the TRACE method");
  331. }
  332. $body = strtolower($res->getBody());
  333. foreach ($headers as $key => $val) {
  334. if (is_array($val))
  335. $val = implode(', ', $val);
  336. $this->assertContains(strtolower("$key: $val"), $body);
  337. }
  338. }
  339. /**
  340. * Redirection tests
  341. */
  342. /**
  343. * Test the client properly redirects in default mode
  344. *
  345. */
  346. public function testRedirectDefault()
  347. {
  348. $this->client->setUri($this->baseuri . 'testRedirections.php');
  349. // Set some parameters
  350. $this->client->setParameterGet('swallow', 'african');
  351. $this->client->setParameterPost('Camelot', 'A silly place');
  352. // Request
  353. $res = $this->client->request('POST');
  354. $this->assertEquals(3, $this->client->getRedirectionsCount(), 'Redirection counter is not as expected');
  355. // Make sure the body does *not* contain the set parameters
  356. $this->assertNotContains('swallow', $res->getBody());
  357. $this->assertNotContains('Camelot', $res->getBody());
  358. }
  359. /**
  360. * Make sure the client properly redirects in strict mode
  361. *
  362. */
  363. public function testRedirectStrict()
  364. {
  365. $this->client->setUri($this->baseuri . 'testRedirections.php');
  366. // Set some parameters
  367. $this->client->setParameterGet('swallow', 'african');
  368. $this->client->setParameterPost('Camelot', 'A silly place');
  369. // Set strict redirections
  370. $this->client->setConfig(array('strictredirects' => true));
  371. // Request
  372. $res = $this->client->request('POST');
  373. $this->assertEquals(3, $this->client->getRedirectionsCount(), 'Redirection counter is not as expected');
  374. // Make sure the body *does* contain the set parameters
  375. $this->assertContains('swallow', $res->getBody());
  376. $this->assertContains('Camelot', $res->getBody());
  377. }
  378. /**
  379. * Make sure redirections stop when limit is exceeded
  380. *
  381. */
  382. public function testMaxRedirectsExceeded()
  383. {
  384. $this->client->setUri($this->baseuri . 'testRedirections.php');
  385. // Set some parameters
  386. $this->client->setParameterGet('swallow', 'african');
  387. $this->client->setParameterPost('Camelot', 'A silly place');
  388. // Set lower max redirections
  389. // Try with strict redirections first
  390. $this->client->setConfig(array('strictredirects' => true, 'maxredirects' => 2));
  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 on)");
  394. // Then try with normal redirections
  395. $this->client->setParameterGet('redirection', '0');
  396. $this->client->setConfig(array('strictredirects' => false));
  397. $res = $this->client->request('POST');
  398. $this->assertTrue($res->isRedirect(),
  399. "Last response was not a redirection as expected. Response code: {$res->getStatus()}. Redirections counter: {$this->client->getRedirectionsCount()} (when strict redirects are off)");
  400. }
  401. /**
  402. * Test we can properly redirect to an absolute path (not full URI)
  403. *
  404. */
  405. public function testAbsolutePathRedirect()
  406. {
  407. $this->client->setUri($this->baseuri . 'testRelativeRedirections.php');
  408. $this->client->setParameterGet('redirect', 'abpath');
  409. $this->client->setConfig(array('maxredirects' => 1));
  410. // Get the host and port part of our baseuri
  411. $uri = $this->client->getUri()->getScheme() . '://' . $this->client->getUri()->getHost() . ':' .
  412. $this->client->getUri()->getPort();
  413. $res = $this->client->request('GET');
  414. $this->assertEquals("{$uri}/path/to/fake/file.ext?redirect=abpath", $this->client->getUri(true),
  415. "The new location is not as expected: {$this->client->getUri(true)}");
  416. }
  417. /**
  418. * Test we can properly redirect to a relative path
  419. *
  420. */
  421. public function testRelativePathRedirect()
  422. {
  423. $this->client->setUri($this->baseuri . 'testRelativeRedirections.php');
  424. $this->client->setParameterGet('redirect', 'relpath');
  425. $this->client->setConfig(array('maxredirects' => 1));
  426. // Set the new expected URI
  427. $uri = clone $this->client->getUri();
  428. // $uri->setPort(80);
  429. $uri->setPath(dirname($uri->getPath()) . '/path/to/fake/file.ext');
  430. $uri = $uri->__toString();
  431. $res = $this->client->request('GET');
  432. $this->assertEquals("{$uri}?redirect=relpath", $this->client->getUri(true),
  433. "The new location is not as expected: {$this->client->getUri(true)}");
  434. }
  435. /**
  436. * HTTP Authentication Tests
  437. *
  438. */
  439. /**
  440. * Test we can properly use Basic HTTP authentication
  441. *
  442. */
  443. public function testHttpAuthBasic()
  444. {
  445. $this->client->setUri($this->baseuri. 'testHttpAuth.php');
  446. $this->client->setParameterGet(array(
  447. 'user' => 'alice',
  448. 'pass' => 'secret',
  449. 'method' => 'Basic'
  450. ));
  451. // First - fail password
  452. $this->client->setAuth('alice', 'wrong');
  453. $res = $this->client->request();
  454. $this->assertEquals(401, $res->getStatus(), 'Expected HTTP 401 response was not recieved');
  455. // Now use good password
  456. $this->client->setAuth('alice', 'secret');
  457. $res = $this->client->request();
  458. $this->assertEquals(200, $res->getStatus(), 'Expected HTTP 200 response was not recieved');
  459. }
  460. /**
  461. * Test we can unset HTTP authentication
  462. *
  463. */
  464. public function testCancelAuth()
  465. {
  466. $this->client->setUri($this->baseuri. 'testHttpAuth.php');
  467. // Set auth and cancel it
  468. $this->client->setAuth('alice', 'secret');
  469. $this->client->setAuth(false);
  470. $res = $this->client->request();
  471. $this->assertEquals(401, $res->getStatus(), 'Expected HTTP 401 response was not recieved');
  472. $this->assertNotContains('alice', $res->getBody(), "Body contains the user name, but it shouldn't");
  473. $this->assertNotContains('secret', $res->getBody(), "Body contains the password, but it shouldn't");
  474. }
  475. /**
  476. * Cookie and CookieJar Tests
  477. *
  478. */
  479. /**
  480. * Test we can set string cookies with no jar
  481. *
  482. */
  483. public function testCookiesStringNoJar()
  484. {
  485. $this->client->setUri($this->baseuri. 'testCookies.php');
  486. $cookies = array(
  487. 'name' => 'value',
  488. 'cookie' => 'crumble'
  489. );
  490. foreach ($cookies as $k => $v) {
  491. $this->client->setCookie($k, $v);
  492. }
  493. $res = $this->client->request();
  494. $this->assertEquals($res->getBody(), serialize($cookies), 'Response body does not contain the expected cookies');
  495. }
  496. /**
  497. * Make sure we can set object cookies with no jar
  498. *
  499. */
  500. public function testSetCookieObjectNoJar()
  501. {
  502. $this->client->setUri($this->baseuri. 'testCookies.php');
  503. $refuri = $this->client->getUri();
  504. $cookies = array(
  505. Zend_Http_Cookie::fromString('chocolate=chips', $refuri),
  506. Zend_Http_Cookie::fromString('crumble=apple', $refuri)
  507. );
  508. $strcookies = array();
  509. foreach ($cookies as $c) {
  510. $this->client->setCookie($c);
  511. $strcookies[$c->getName()] = $c->getValue();
  512. }
  513. $res = $this->client->request();
  514. $this->assertEquals($res->getBody(), serialize($strcookies), 'Response body does not contain the expected cookies');
  515. }
  516. /**
  517. * Make sure we can set an array of object cookies
  518. *
  519. */
  520. public function testSetCookieObjectArray()
  521. {
  522. $this->client->setUri($this->baseuri. 'testCookies.php');
  523. $refuri = $this->client->getUri();
  524. $cookies = array(
  525. Zend_Http_Cookie::fromString('chocolate=chips', $refuri),
  526. Zend_Http_Cookie::fromString('crumble=apple', $refuri),
  527. Zend_Http_Cookie::fromString('another=cookie', $refuri)
  528. );
  529. $this->client->setCookie($cookies);
  530. $strcookies = array();
  531. foreach ($cookies as $c) {
  532. $strcookies[$c->getName()] = $c->getValue();
  533. }
  534. $res = $this->client->request();
  535. $this->assertEquals($res->getBody(), serialize($strcookies), 'Response body does not contain the expected cookies');
  536. }
  537. /**
  538. * Make sure we can set an array of string cookies
  539. *
  540. */
  541. public function testSetCookieStringArray()
  542. {
  543. $this->client->setUri($this->baseuri. 'testCookies.php');
  544. $cookies = array(
  545. 'chocolate' => 'chips',
  546. 'crumble' => 'apple',
  547. 'another' => 'cookie'
  548. );
  549. $this->client->setCookie($cookies);
  550. $res = $this->client->request();
  551. $this->assertEquals($res->getBody(), serialize($cookies), 'Response body does not contain the expected cookies');
  552. }
  553. /**
  554. * Make sure we can set cookie objects with a jar
  555. *
  556. */
  557. public function testSetCookieObjectJar()
  558. {
  559. $this->client->setUri($this->baseuri. 'testCookies.php');
  560. $this->client->setCookieJar();
  561. $refuri = $this->client->getUri();
  562. $cookies = array(
  563. Zend_Http_Cookie::fromString('chocolate=chips', $refuri),
  564. Zend_Http_Cookie::fromString('crumble=apple', $refuri)
  565. );
  566. $strcookies = array();
  567. foreach ($cookies as $c) {
  568. $this->client->setCookie($c);
  569. $strcookies[$c->getName()] = $c->getValue();
  570. }
  571. $res = $this->client->request();
  572. $this->assertEquals($res->getBody(), serialize($strcookies), 'Response body does not contain the expected cookies');
  573. }
  574. /**
  575. * File Upload Tests
  576. *
  577. */
  578. /**
  579. * Test we can upload raw data as a file
  580. *
  581. */
  582. public function testUploadRawData()
  583. {
  584. $this->client->setUri($this->baseuri. 'testUploads.php');
  585. $rawdata = file_get_contents(__FILE__);
  586. $this->client->setFileUpload('myfile.txt', 'uploadfile', $rawdata, 'text/plain');
  587. $res = $this->client->request('POST');
  588. $body = 'uploadfile myfile.txt text/plain ' . strlen($rawdata) . "\n";
  589. $this->assertEquals($body, $res->getBody(), 'Response body does not include expected upload parameters');
  590. }
  591. /**
  592. * Test we can upload an existing file
  593. *
  594. */
  595. public function testUploadLocalFile()
  596. {
  597. $this->client->setUri($this->baseuri. 'testUploads.php');
  598. $this->client->setFileUpload(__FILE__, 'uploadfile', null, 'text/x-foo-bar');
  599. $res = $this->client->request('POST');
  600. $size = filesize(__FILE__);
  601. $body = "uploadfile " . basename(__FILE__) . " text/x-foo-bar $size\n";
  602. $this->assertEquals($body, $res->getBody(), 'Response body does not include expected upload parameters');
  603. }
  604. public function testUploadLocalDetectMime()
  605. {
  606. $detect = null;
  607. if (function_exists('finfo_file')) {
  608. $f = @finfo_open(FILEINFO_MIME);
  609. if ($f) $detect = 'finfo';
  610. } elseif (function_exists('mime_content_type')) {
  611. if (mime_content_type(__FILE__)) {
  612. $detect = 'mime_magic';
  613. }
  614. }
  615. if (! $detect) {
  616. $this->markTestSkipped('No MIME type detection capability (fileinfo or mime_magic extensions) is available');
  617. }
  618. $file = dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR . 'staticFile.jpg';
  619. $this->client->setUri($this->baseuri. 'testUploads.php');
  620. $this->client->setFileUpload($file, 'uploadfile');
  621. $res = $this->client->request('POST');
  622. $size = filesize($file);
  623. $body = "uploadfile " . basename($file) . " image/jpeg $size\n";
  624. $this->assertEquals($body, $res->getBody(), 'Response body does not include expected upload parameters (detect: ' . $detect . ')');
  625. }
  626. public function testUploadNameWithSpecialChars()
  627. {
  628. $this->client->setUri($this->baseuri. 'testUploads.php');
  629. $rawdata = file_get_contents(__FILE__);
  630. $this->client->setFileUpload('/some strage/path%/with[!@#$&]/myfile.txt', 'uploadfile', $rawdata, 'text/plain');
  631. $res = $this->client->request('POST');
  632. $body = 'uploadfile myfile.txt text/plain ' . strlen($rawdata) . "\n";
  633. $this->assertEquals($body, $res->getBody(), 'Response body does not include expected upload parameters');
  634. }
  635. public function testStaticLargeFileDownload()
  636. {
  637. $this->client->setUri($this->baseuri . 'staticFile.jpg');
  638. $got = $this->client->request()->getBody();
  639. $expected = $this->_getTestFileContents('staticFile.jpg');
  640. $this->assertEquals($expected, $got, 'Downloaded file does not seem to match!');
  641. }
  642. /**
  643. * Test that one can upload multiple files with the same form name, as an
  644. * array
  645. *
  646. * @link http://framework.zend.com/issues/browse/ZF-5744
  647. */
  648. public function testMutipleFilesWithSameFormNameZF5744()
  649. {
  650. $rawData = 'Some test raw data here...';
  651. $this->client->setUri($this->baseuri . 'testUploads.php');
  652. $files = array('file1.txt', 'file2.txt', 'someotherfile.foo');
  653. $expectedBody = '';
  654. foreach($files as $filename) {
  655. $this->client->setFileUpload($filename, 'uploadfile[]', $rawData, 'text/plain');
  656. $expectedBody .= "uploadfile $filename text/plain " . strlen($rawData) . "\n";
  657. }
  658. $res = $this->client->request('POST');
  659. $this->assertEquals($expectedBody, $res->getBody(), 'Response body does not include expected upload parameters');
  660. }
  661. /**
  662. * Test that lines that might be evaluated as boolean false do not break
  663. * the reading prematurely.
  664. *
  665. * @see http://framework.zend.com/issues/browse/ZF-4238
  666. */
  667. public function testZF4238FalseLinesInResponse()
  668. {
  669. $this->client->setUri($this->baseuri . 'ZF4238-zerolineresponse.txt');
  670. $got = $this->client->request()->getBody();
  671. $expected = $this->_getTestFileContents('ZF4238-zerolineresponse.txt');
  672. $this->assertEquals($expected, $got);
  673. }
  674. /**
  675. * Internal helpder function to get the contents of test files
  676. *
  677. * @param string $file
  678. * @return string
  679. */
  680. protected function _getTestFileContents($file)
  681. {
  682. return file_get_contents(dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR .
  683. '_files' . DIRECTORY_SEPARATOR . $file);
  684. }
  685. }