HttpfulTest.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. <?php
  2. /**
  3. * Port over the original tests into a more traditional PHPUnit
  4. * format. Still need to hook into a lightweight HTTP server to
  5. * better test some things (e.g. obscure cURL settings). I've moved
  6. * the old tests and node.js server to the tests/.legacy directory.
  7. *
  8. * @author Nate Good <me@nategood.com>
  9. */
  10. namespace Httpful\Test;
  11. require(dirname(dirname(dirname(__FILE__))) . '/bootstrap.php');
  12. \Httpful\Bootstrap::init();
  13. use Httpful\Httpful;
  14. use Httpful\Request;
  15. use Httpful\Mime;
  16. use Httpful\Http;
  17. use Httpful\Response;
  18. use Httpful\Handlers\JsonHandler;
  19. define('TEST_SERVER', WEB_SERVER_HOST . ':' . WEB_SERVER_PORT);
  20. class HttpfulTest extends \PHPUnit\Framework\TestCase
  21. {
  22. const TEST_SERVER = TEST_SERVER;
  23. const TEST_URL = 'http://127.0.0.1:8008';
  24. const TEST_URL_400 = 'http://127.0.0.1:8008/400';
  25. const SAMPLE_JSON_HEADER =
  26. "HTTP/1.1 200 OK
  27. Content-Type: application/json
  28. Connection: keep-alive
  29. Transfer-Encoding: chunked\r\n";
  30. const SAMPLE_JSON_HEADER_LOWERCASE =
  31. "HTTP/2 200
  32. date: Tue, 07 Jan 2020 09:11:21 GMT
  33. content-type: application/json
  34. content-length: 513
  35. access-control-allow-origin: *
  36. access-control-allow-methods: GET, POST, PUT, PATCH, DELETE
  37. access-control-allow-headers: Authorization, Content-Type, Accept-Encoding, Cache-Control, DNT
  38. cache-control: private, must-revalidate\r\n";
  39. const SAMPLE_JSON_RESPONSE = '{"key":"value","object":{"key":"value"},"array":[1,2,3,4]}';
  40. const SAMPLE_CSV_HEADER =
  41. "HTTP/1.1 200 OK
  42. Content-Type: text/csv
  43. Connection: keep-alive
  44. Transfer-Encoding: chunked\r\n";
  45. const SAMPLE_CSV_RESPONSE =
  46. "Key1,Key2
  47. Value1,Value2
  48. \"40.0\",\"Forty\"";
  49. const SAMPLE_XML_RESPONSE = '<stdClass><arrayProp><array><k1><myClass><intProp>2</intProp></myClass></k1></array></arrayProp><stringProp>a string</stringProp><boolProp>TRUE</boolProp></stdClass>';
  50. const SAMPLE_XML_HEADER =
  51. "HTTP/1.1 200 OK
  52. Content-Type: application/xml
  53. Connection: keep-alive
  54. Transfer-Encoding: chunked\r\n";
  55. const SAMPLE_VENDOR_HEADER =
  56. "HTTP/1.1 200 OK
  57. Content-Type: application/vnd.nategood.message+xml
  58. Connection: keep-alive
  59. Transfer-Encoding: chunked\r\n";
  60. const SAMPLE_VENDOR_TYPE = "application/vnd.nategood.message+xml";
  61. const SAMPLE_MULTI_HEADER =
  62. "HTTP/1.1 200 OK
  63. Content-Type: application/json
  64. Connection: keep-alive
  65. Transfer-Encoding: chunked
  66. X-My-Header:Value1
  67. X-My-Header:Value2\r\n";
  68. function testInit()
  69. {
  70. $r = Request::init();
  71. // Did we get a 'Request' object?
  72. $this->assertEquals('Httpful\Request', get_class($r));
  73. }
  74. function testDetermineLength()
  75. {
  76. $r = Request::init();
  77. $this->assertEquals(1, $r->_determineLength('A'));
  78. $this->assertEquals(2, $r->_determineLength('À'));
  79. $this->assertEquals(2, $r->_determineLength('Ab'));
  80. $this->assertEquals(3, $r->_determineLength('Àb'));
  81. $this->assertEquals(6, $r->_determineLength('世界'));
  82. }
  83. function testMethods()
  84. {
  85. $valid_methods = array('get', 'post', 'delete', 'put', 'options', 'head');
  86. $url = 'http://example.com/';
  87. foreach ($valid_methods as $method) {
  88. $r = call_user_func(array('Httpful\Request', $method), $url);
  89. $this->assertEquals('Httpful\Request', get_class($r));
  90. $this->assertEquals(strtoupper($method), $r->method);
  91. }
  92. }
  93. function testDefaults()
  94. {
  95. // Our current defaults are as follows
  96. $r = Request::init();
  97. $this->assertEquals(Http::GET, $r->method);
  98. $this->assertFalse($r->strict_ssl);
  99. }
  100. function testShortMime()
  101. {
  102. // Valid short ones
  103. $this->assertEquals(Mime::JSON, Mime::getFullMime('json'));
  104. $this->assertEquals(Mime::XML, Mime::getFullMime('xml'));
  105. $this->assertEquals(Mime::HTML, Mime::getFullMime('html'));
  106. $this->assertEquals(Mime::CSV, Mime::getFullMime('csv'));
  107. $this->assertEquals(Mime::UPLOAD, Mime::getFullMime('upload'));
  108. // Valid long ones
  109. $this->assertEquals(Mime::JSON, Mime::getFullMime(Mime::JSON));
  110. $this->assertEquals(Mime::XML, Mime::getFullMime(Mime::XML));
  111. $this->assertEquals(Mime::HTML, Mime::getFullMime(Mime::HTML));
  112. $this->assertEquals(Mime::CSV, Mime::getFullMime(Mime::CSV));
  113. $this->assertEquals(Mime::UPLOAD, Mime::getFullMime(Mime::UPLOAD));
  114. // No false positives
  115. $this->assertNotEquals(Mime::XML, Mime::getFullMime(Mime::HTML));
  116. $this->assertNotEquals(Mime::JSON, Mime::getFullMime(Mime::XML));
  117. $this->assertNotEquals(Mime::HTML, Mime::getFullMime(Mime::JSON));
  118. $this->assertNotEquals(Mime::XML, Mime::getFullMime(Mime::CSV));
  119. }
  120. function testSettingStrictSsl()
  121. {
  122. $r = Request::init()
  123. ->withStrictSsl();
  124. $this->assertTrue($r->strict_ssl);
  125. $r = Request::init()
  126. ->withoutStrictSsl();
  127. $this->assertFalse($r->strict_ssl);
  128. }
  129. function testSendsAndExpectsType()
  130. {
  131. $r = Request::init()
  132. ->sendsAndExpectsType(Mime::JSON);
  133. $this->assertEquals(Mime::JSON, $r->expected_type);
  134. $this->assertEquals(Mime::JSON, $r->content_type);
  135. $r = Request::init()
  136. ->sendsAndExpectsType('html');
  137. $this->assertEquals(Mime::HTML, $r->expected_type);
  138. $this->assertEquals(Mime::HTML, $r->content_type);
  139. $r = Request::init()
  140. ->sendsAndExpectsType('form');
  141. $this->assertEquals(Mime::FORM, $r->expected_type);
  142. $this->assertEquals(Mime::FORM, $r->content_type);
  143. $r = Request::init()
  144. ->sendsAndExpectsType('application/x-www-form-urlencoded');
  145. $this->assertEquals(Mime::FORM, $r->expected_type);
  146. $this->assertEquals(Mime::FORM, $r->content_type);
  147. $r = Request::init()
  148. ->sendsAndExpectsType(Mime::CSV);
  149. $this->assertEquals(Mime::CSV, $r->expected_type);
  150. $this->assertEquals(Mime::CSV, $r->content_type);
  151. }
  152. function testIni()
  153. {
  154. // Test setting defaults/templates
  155. // Create the template
  156. $template = Request::init()
  157. ->method(Http::POST)
  158. ->withStrictSsl()
  159. ->expectsType(Mime::HTML)
  160. ->sendsType(Mime::FORM);
  161. Request::ini($template);
  162. $r = Request::init();
  163. $this->assertTrue($r->strict_ssl);
  164. $this->assertEquals(Http::POST, $r->method);
  165. $this->assertEquals(Mime::HTML, $r->expected_type);
  166. $this->assertEquals(Mime::FORM, $r->content_type);
  167. // Test the default accessor as well
  168. $this->assertTrue(Request::d('strict_ssl'));
  169. $this->assertEquals(Http::POST, Request::d('method'));
  170. $this->assertEquals(Mime::HTML, Request::d('expected_type'));
  171. $this->assertEquals(Mime::FORM, Request::d('content_type'));
  172. Request::resetIni();
  173. }
  174. function testAccept()
  175. {
  176. $r = Request::get('http://example.com/')
  177. ->expectsType(Mime::JSON);
  178. $this->assertEquals(Mime::JSON, $r->expected_type);
  179. $r->_curlPrep();
  180. $this->assertStringContainsString('application/json', $r->raw_headers);
  181. }
  182. function testCustomAccept()
  183. {
  184. $accept = 'application/api-1.0+json';
  185. $r = Request::get('http://example.com/')
  186. ->addHeader('Accept', $accept);
  187. $r->_curlPrep();
  188. $this->assertStringContainsString($accept, $r->raw_headers);
  189. $this->assertEquals($accept, $r->headers['Accept']);
  190. }
  191. function testUserAgent()
  192. {
  193. $r = Request::get('http://example.com/')
  194. ->withUserAgent('ACME/1.2.3');
  195. $this->assertArrayHasKey('User-Agent', $r->headers);
  196. $r->_curlPrep();
  197. $this->assertStringContainsString('User-Agent: ACME/1.2.3', $r->raw_headers);
  198. $this->assertStringNotContainsString('User-Agent: HttpFul/1.0', $r->raw_headers);
  199. $r = Request::get('http://example.com/')
  200. ->withUserAgent('');
  201. $this->assertArrayHasKey('User-Agent', $r->headers);
  202. $r->_curlPrep();
  203. $this->assertStringContainsString('User-Agent:', $r->raw_headers);
  204. $this->assertStringNotContainsString('User-Agent: HttpFul/1.0', $r->raw_headers);
  205. }
  206. function testAuthSetup()
  207. {
  208. $username = 'nathan';
  209. $password = 'opensesame';
  210. $r = Request::get('http://example.com/')
  211. ->authenticateWith($username, $password);
  212. $this->assertEquals($username, $r->username);
  213. $this->assertEquals($password, $r->password);
  214. $this->assertTrue($r->hasBasicAuth());
  215. }
  216. function testDigestAuthSetup()
  217. {
  218. $username = 'nathan';
  219. $password = 'opensesame';
  220. $r = Request::get('http://example.com/')
  221. ->authenticateWithDigest($username, $password);
  222. $this->assertEquals($username, $r->username);
  223. $this->assertEquals($password, $r->password);
  224. $this->assertTrue($r->hasDigestAuth());
  225. }
  226. function testJsonResponseParse()
  227. {
  228. $req = Request::init()->sendsAndExpects(Mime::JSON);
  229. $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
  230. $this->assertEquals("value", $response->body->key);
  231. $this->assertEquals("value", $response->body->object->key);
  232. $this->assertIsArray( $response->body->array);
  233. $this->assertEquals(1, $response->body->array[0]);
  234. }
  235. function testJsonResponseParseLowercaseHeaders()
  236. {
  237. $req = Request::init();
  238. $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER_LOWERCASE, $req);
  239. $this->assertEquals("value", $response->body->key);
  240. $this->assertEquals("value", $response->body->object->key);
  241. $this->assertIsArray( $response->body->array);
  242. $this->assertEquals(1, $response->body->array[0]);
  243. }
  244. function testXMLResponseParse()
  245. {
  246. $req = Request::init()->sendsAndExpects(Mime::XML);
  247. $response = new Response(self::SAMPLE_XML_RESPONSE, self::SAMPLE_XML_HEADER, $req);
  248. $sxe = $response->body;
  249. $this->assertEquals("object", gettype($sxe));
  250. $this->assertEquals("SimpleXMLElement", get_class($sxe));
  251. $bools = $sxe->xpath('/stdClass/boolProp');
  252. // list( , $bool ) = each($bools);
  253. $bool = array_shift($bools);
  254. $this->assertEquals("TRUE", (string) $bool);
  255. $ints = $sxe->xpath('/stdClass/arrayProp/array/k1/myClass/intProp');
  256. // list( , $int ) = each($ints);
  257. $int = array_shift($ints);
  258. $this->assertEquals("2", (string) $int);
  259. $strings = $sxe->xpath('/stdClass/stringProp');
  260. // list( , $string ) = each($strings);
  261. $string = array_shift($strings);
  262. $this->assertEquals("a string", (string) $string);
  263. }
  264. function testCsvResponseParse()
  265. {
  266. $req = Request::init()->sendsAndExpects(Mime::CSV);
  267. $response = new Response(self::SAMPLE_CSV_RESPONSE, self::SAMPLE_CSV_HEADER, $req);
  268. $this->assertEquals("Key1", $response->body[0][0]);
  269. $this->assertEquals("Value1", $response->body[1][0]);
  270. $this->assertIsString( $response->body[2][0]);
  271. $this->assertEquals("40.0", $response->body[2][0]);
  272. }
  273. function testParsingContentTypeCharset()
  274. {
  275. $req = Request::init()->sendsAndExpects(Mime::JSON);
  276. // $response = new Response(SAMPLE_JSON_RESPONSE, "", $req);
  277. // // Check default content type of iso-8859-1
  278. $response = new Response(self::SAMPLE_JSON_RESPONSE, "HTTP/1.1 200 OK
  279. Content-Type: text/plain; charset=utf-8\r\n", $req);
  280. $this->assertInstanceOf('Httpful\Response\Headers', $response->headers);
  281. $this->assertEquals($response->headers['Content-Type'], 'text/plain; charset=utf-8');
  282. $this->assertEquals($response->content_type, 'text/plain');
  283. $this->assertEquals($response->charset, 'utf-8');
  284. }
  285. function testParsingContentTypeUpload()
  286. {
  287. $req = Request::init();
  288. $req->sendsType(Mime::UPLOAD);
  289. // $response = new Response(SAMPLE_JSON_RESPONSE, "", $req);
  290. // // Check default content type of iso-8859-1
  291. $this->assertEquals($req->content_type, 'multipart/form-data');
  292. }
  293. function testAttach() {
  294. $req = Request::init();
  295. $testsPath = realpath(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..');
  296. $filename = $testsPath . DIRECTORY_SEPARATOR . 'test_image.jpg';
  297. $req->attach(array('index' => $filename));
  298. $payload = $req->payload['index'];
  299. // PHP 5.5 + will take advantage of CURLFile while previous
  300. // versions just use the string syntax
  301. if (is_string($payload)) {
  302. $this->assertEquals($payload, '@' . $filename . ';type=image/jpeg');
  303. } else {
  304. $this->assertInstanceOf('CURLFile', $payload);
  305. }
  306. $this->assertEquals($req->content_type, Mime::UPLOAD);
  307. $this->assertEquals($req->serialize_payload_method, Request::SERIALIZE_PAYLOAD_NEVER);
  308. }
  309. function testIsUpload() {
  310. $req = Request::init();
  311. $req->sendsType(Mime::UPLOAD);
  312. $this->assertTrue($req->isUpload());
  313. }
  314. function testEmptyResponseParse()
  315. {
  316. $req = Request::init()->sendsAndExpects(Mime::JSON);
  317. $response = new Response("", self::SAMPLE_JSON_HEADER, $req);
  318. $this->assertEquals(null, $response->body);
  319. $reqXml = Request::init()->sendsAndExpects(Mime::XML);
  320. $responseXml = new Response("", self::SAMPLE_XML_HEADER, $reqXml);
  321. $this->assertEquals(null, $responseXml->body);
  322. }
  323. function testNoAutoParse()
  324. {
  325. $req = Request::init()->sendsAndExpects(Mime::JSON)->withoutAutoParsing();
  326. $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
  327. $this->assertIsString( $response->body);
  328. $req = Request::init()->sendsAndExpects(Mime::JSON)->withAutoParsing();
  329. $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
  330. $this->assertIsObject($response->body);
  331. }
  332. function testParseHeaders()
  333. {
  334. $req = Request::init()->sendsAndExpects(Mime::JSON);
  335. $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
  336. $this->assertEquals('application/json', $response->headers['Content-Type']);
  337. }
  338. function testRawHeaders()
  339. {
  340. $req = Request::init()->sendsAndExpects(Mime::JSON);
  341. $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
  342. $this->assertStringContainsString('Content-Type: application/json', $response->raw_headers);
  343. }
  344. function testHasErrors()
  345. {
  346. $req = Request::init()->sendsAndExpects(Mime::JSON);
  347. $response = new Response('', "HTTP/1.1 100 Continue\r\n", $req);
  348. $this->assertFalse($response->hasErrors());
  349. $response = new Response('', "HTTP/1.1 200 OK\r\n", $req);
  350. $this->assertFalse($response->hasErrors());
  351. $response = new Response('', "HTTP/1.1 300 Multiple Choices\r\n", $req);
  352. $this->assertFalse($response->hasErrors());
  353. $response = new Response('', "HTTP/1.1 400 Bad Request\r\n", $req);
  354. $this->assertTrue($response->hasErrors());
  355. $response = new Response('', "HTTP/1.1 500 Internal Server Error\r\n", $req);
  356. $this->assertTrue($response->hasErrors());
  357. }
  358. function testWhenError() {
  359. $caught = false;
  360. try {
  361. Request::get('malformed:url')
  362. ->whenError(function($error) use(&$caught) {
  363. $caught = true;
  364. })
  365. ->timeoutIn(0.1)
  366. ->send();
  367. } catch (\Httpful\Exception\ConnectionErrorException $e) {}
  368. $this->assertTrue($caught);
  369. }
  370. function testBeforeSend() {
  371. $invoked = false;
  372. $changed = false;
  373. $self = $this;
  374. try {
  375. Request::get('malformed://url')
  376. ->beforeSend(function($request) use(&$invoked,$self) {
  377. $self->assertEquals('malformed://url', $request->uri);
  378. $self->assertEquals('A payload', $request->serialized_payload);
  379. $request->uri('malformed2://url');
  380. $invoked = true;
  381. })
  382. ->whenError(function($error) { /* Be silent */ })
  383. ->body('A payload')
  384. ->send();
  385. } catch (\Httpful\Exception\ConnectionErrorException $e) {
  386. $this->assertTrue(strpos($e->getMessage(), 'malformed2') !== false);
  387. $changed = true;
  388. }
  389. $this->assertTrue($invoked);
  390. $this->assertTrue($changed);
  391. }
  392. function test_parseCode()
  393. {
  394. $req = Request::init()->sendsAndExpects(Mime::JSON);
  395. $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
  396. $code = $response->_parseCode("HTTP/1.1 406 Not Acceptable\r\n");
  397. $this->assertEquals(406, $code);
  398. }
  399. function testToString()
  400. {
  401. $req = Request::init()->sendsAndExpects(Mime::JSON);
  402. $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
  403. $this->assertEquals(self::SAMPLE_JSON_RESPONSE, (string)$response);
  404. }
  405. function test_parseHeaders()
  406. {
  407. $parse_headers = Response\Headers::fromString(self::SAMPLE_JSON_HEADER);
  408. $this->assertCount(3, $parse_headers);
  409. $this->assertEquals('application/json', $parse_headers['Content-Type']);
  410. $this->assertTrue(isset($parse_headers['Connection']));
  411. }
  412. function testMultiHeaders()
  413. {
  414. $req = Request::init();
  415. $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_MULTI_HEADER, $req);
  416. $parse_headers = $response->_parseHeaders(self::SAMPLE_MULTI_HEADER);
  417. $this->assertEquals('Value1,Value2', $parse_headers['X-My-Header']);
  418. }
  419. function testDetectContentType()
  420. {
  421. $req = Request::init();
  422. $response = new Response(self::SAMPLE_JSON_RESPONSE, self::SAMPLE_JSON_HEADER, $req);
  423. $this->assertEquals('application/json', $response->headers['Content-Type']);
  424. }
  425. function testMissingBodyContentType()
  426. {
  427. $body = 'A string';
  428. $request = Request::post(HttpfulTest::TEST_URL, $body)->_curlPrep();
  429. $this->assertEquals($body, $request->serialized_payload);
  430. }
  431. function testParentType()
  432. {
  433. // Parent type
  434. $request = Request::init()->sendsAndExpects(Mime::XML);
  435. $response = new Response('<xml><name>Nathan</name></xml>', self::SAMPLE_VENDOR_HEADER, $request);
  436. $this->assertEquals("application/xml", $response->parent_type);
  437. $this->assertEquals(self::SAMPLE_VENDOR_TYPE, $response->content_type);
  438. $this->assertTrue($response->is_mime_vendor_specific);
  439. // Make sure we still parsed as if it were plain old XML
  440. $this->assertEquals("Nathan", $response->body->name->__toString());
  441. }
  442. function testMissingContentType()
  443. {
  444. // Parent type
  445. $request = Request::init()->sendsAndExpects(Mime::XML);
  446. $response = new Response('<xml><name>Nathan</name></xml>',
  447. "HTTP/1.1 200 OK
  448. Connection: keep-alive
  449. Transfer-Encoding: chunked\r\n", $request);
  450. $this->assertEquals("", $response->content_type);
  451. }
  452. function testCustomMimeRegistering()
  453. {
  454. // Register new mime type handler for "application/vnd.nategood.message+xml"
  455. Httpful::register(self::SAMPLE_VENDOR_TYPE, new DemoMimeHandler());
  456. $this->assertTrue(Httpful::hasParserRegistered(self::SAMPLE_VENDOR_TYPE));
  457. $request = Request::init();
  458. $response = new Response('<xml><name>Nathan</name></xml>', self::SAMPLE_VENDOR_HEADER, $request);
  459. $this->assertEquals(self::SAMPLE_VENDOR_TYPE, $response->content_type);
  460. $this->assertEquals('custom parse', $response->body);
  461. }
  462. public function testShorthandMimeDefinition()
  463. {
  464. $r = Request::init()->expects('json');
  465. $this->assertEquals(Mime::JSON, $r->expected_type);
  466. $r = Request::init()->expectsJson();
  467. $this->assertEquals(Mime::JSON, $r->expected_type);
  468. }
  469. public function testOverrideXmlHandler()
  470. {
  471. // Lazy test...
  472. $prev = \Httpful\Httpful::get(\Httpful\Mime::XML);
  473. $this->assertEquals($prev, new \Httpful\Handlers\XmlHandler());
  474. $conf = array('namespace' => 'http://example.com');
  475. \Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf));
  476. $new = \Httpful\Httpful::get(\Httpful\Mime::XML);
  477. $this->assertNotEquals($prev, $new);
  478. }
  479. public function testHasProxyWithoutProxy()
  480. {
  481. $r = Request::get('someUrl');
  482. $this->assertFalse($r->hasProxy());
  483. }
  484. public function testHasProxyWithProxy()
  485. {
  486. $r = Request::get('some_other_url');
  487. $r->useProxy('proxy.com');
  488. $this->assertTrue($r->hasProxy());
  489. }
  490. public function testHasProxyWithEnvironmentProxy()
  491. {
  492. putenv('http_proxy=http://127.0.0.1:300/');
  493. $r = Request::get('some_other_url');
  494. $this->assertTrue($r->hasProxy());
  495. }
  496. public function testParseJSON()
  497. {
  498. $handler = new JsonHandler();
  499. $bodies = array(
  500. 'foo',
  501. array(),
  502. array('foo', 'bar'),
  503. null
  504. );
  505. foreach ($bodies as $body) {
  506. $this->assertEquals($body, $handler->parse(json_encode($body)));
  507. }
  508. try {
  509. $result = $handler->parse('invalid{json');
  510. } catch (\Httpful\Exception\JsonParseException $e) {
  511. $this->assertEquals('Unable to parse response as JSON: ' . json_last_error_msg(), $e->getMessage());
  512. return;
  513. }
  514. $this->fail('Expected an exception to be thrown due to invalid json');
  515. }
  516. // /**
  517. // * Skeleton for testing against the 5.4 baked in server
  518. // */
  519. // public function testLocalServer()
  520. // {
  521. // if (!defined('WITHOUT_SERVER') || (defined('WITHOUT_SERVER') && !WITHOUT_SERVER)) {
  522. // // PHP test server seems to always set content type to application/octet-stream
  523. // // so force parsing as JSON here
  524. // Httpful::register('application/octet-stream', new \Httpful\Handlers\JsonHandler());
  525. // $response = Request::get(TEST_SERVER . '/test.json')
  526. // ->sendsAndExpects(MIME::JSON);
  527. // $response->send();
  528. // $this->assertTrue(...);
  529. // }
  530. // }
  531. }
  532. class DemoMimeHandler extends \Httpful\Handlers\MimeHandlerAdapter
  533. {
  534. public function parse($body)
  535. {
  536. return 'custom parse';
  537. }
  538. }