/**
  * Setup a `\HTTP_Request2_Response` with the given type!
  *
  * @param string $func Type of all: getConnection, getUsers
  * @param string $type 'success' or 'failure'
  *
  * @return \HTTP_Request2_Response
  */
 protected function getResponse($func, $type = 'success')
 {
     $response = new \HTTP_Request2_Response('HTTP/1.1 200');
     $json = file_get_contents(dirname(dirname(dirname(__DIR__))) . '/fixtures/' . $func . '/' . $type . '.json');
     $response->appendBody($json);
     return $response;
 }
Example #2
0
 public function testGetDataFromBody()
 {
     $response = new HTTP_Request2_Response('HTTP/1.1 200 OK');
     $response->appendBody('oauth_token=foo&oauth_token_secret=bar');
     $res = new HTTP_OAuth_Consumer_Response($response);
     $this->assertEquals(array('oauth_token' => 'foo', 'oauth_token_secret' => 'bar'), $res->getDataFromBody());
 }
Example #3
0
/**
 * Returns an instance of Services_Twitter.
 *
 * @param string $ep      The endpoint to call (eg. )
 * @param bool   $auth    Whether to authenticate or not
 * @param array  $options An optional options array to pass to the 
 *                        Services_Twitter constructor
 *
 * @return Services_Twitter The twitter instance.
 */
function Services_Twitter_factory($ep, $auth = true, $options = array())
{
    //$options['raw_format'] = true;
    global $config;
    if ($auth) {
        $twitter = new Services_Twitter($config['user'], $config['pass'], $options);
    } else {
        $twitter = new Services_Twitter(null, null, $options);
    }
    if (!$config['live_test']) {
        if ($ep == 'exception1') {
            $resp = new HTTP_Request2_Response('HTTP/1.1 401 Unauthorized', false);
            $resp->appendBody('{"request":"\\/statuses\\/friends_timeline.json", ' . '"error":"Could not authenticate you."}');
        } else {
            if ($ep == 'exception2') {
                $resp = new HTTP_Request2_Response('HTTP/1.1 404 Not Found', false);
            } else {
                $resp = new HTTP_Request2_Response('HTTP/1.1 200 Success', false);
                $file = dirname(__FILE__) . '/data/' . $ep . '.dat';
                $resp->appendBody(file_get_contents($file));
            }
        }
        $mock = new HTTP_Request2_Adapter_Mock();
        $mock->addResponse($resp);
        $request = $twitter->getRequest()->setAdapter($mock);
    }
    return $twitter;
}
/**
 * Return the Services_GeoNames with either a mock adapter or the real adapter
 * depending whether the SERVICES_GEONAMES_LIVETEST environment variable is set
 * or not.
 *
 * @param string $testname The test name (without extension)
 * @param string $user     Username (optional)
 * @param string $token    Auth token (optional)
 *
 * @return Services_GeoNames
 */
function Services_GeoNames_factory($testname, $user = null, $token = null)
{
    $geo = new Services_GeoNames($user, $token);
    if (!getenv('SERVICES_GEONAMES_LIVETEST')) {
        // test with a mock adapter
        $mock = new HTTP_Request2_Adapter_Mock();
        if ($testname == 'test_other_04') {
            $resp = new HTTP_Request2_Response('HTTP/1.1 404 Not Found', false);
        } else {
            if ($testname == 'test_other_07') {
                $resp = new HTTP_Request2_Response('HTTP/1.1 404 Not Found', false);
                $mock->addResponse($resp);
                $resp = new HTTP_Request2_Response('HTTP/1.1 404 Not Found', false);
                $mock->addResponse($resp);
                $resp = new HTTP_Request2_Response('HTTP/1.1 404 Not Found', false);
            } else {
                $resp = new HTTP_Request2_Response('HTTP/1.1 200 Success', false);
                $file = dirname(__FILE__) . '/data/' . $testname . '.dat';
                $resp->appendBody(file_get_contents($file));
            }
        }
        $mock->addResponse($resp);
        $geo->getRequest()->setAdapter($mock);
    }
    return $geo;
}
 /**
  * Tests the returned result of {@link Solr::query()}.
  */
 function testQuery()
 {
     $response = new HTTP_Request2_Response('HTTP/1.0 200 OK');
     $solrResponse = '{"responseHeader":{"status":0,"QTime":0,"params":{"q":"php","qt":"standard","wt":"json"}},"response":{"numFound":1,"start":0,"docs":[{"id":42,"title":"PHP 5"}]}}';
     $response->appendBody($solrResponse);
     $this->httpClientMock->expects($this->once())->method('sendRequest')->with($this->equalTo('/select?qt=standard&wt=json&q=php'))->will($this->returnValue($response));
     $this->assertEquals(SolrSearchResult::parseResponse($solrResponse), $this->solr->query('php'));
 }
Example #6
0
 /**
  * Callback function called by cURL for saving the response body
  *
  * @param    resource    cURL handle (not used)
  * @param    string      part of the response body
  * @return   integer     number of bytes saved
  * @see      HTTP_Request2_Response::appendBody()
  */
 protected function callbackWriteBody($ch, $string)
 {
     // cURL calls WRITEFUNCTION callback without calling HEADERFUNCTION if
     // response doesn't start with proper HTTP status line (see bug #15716)
     if (empty($this->response)) {
         throw new HTTP_Request2_MessageException("Malformed response: {$string}", HTTP_Request2_Exception::MALFORMED_RESPONSE);
     }
     if ($this->request->getConfig('store_body')) {
         $this->response->appendBody($string);
     }
     $this->request->setLastEvent('receivedBodyPart', $string);
     return strlen($string);
 }
 public function setUp()
 {
     parent::setUp();
     Yii::configure(Yii::$app, ['components' => ['user' => ['class' => 'yii\\web\\User', 'identityClass' => 'common\\models\\User'], 'p24' => ['class' => \merigold\przelewy24\src\Przelewy24Component::className(), 'merchant_id' => $this->merchant_id, 'pos_id' => $this->merchant_id, 'CRC' => $this->CRC]]]);
     Yii::$container->set('HTTP_Request2', function () {
         $response = new HTTP_Request2_Response("HTTP/1.1 200 OK", true);
         $response->appendBody($this->succesresponse);
         $mockAdapter = new HTTP_Request2_Adapter_Mock();
         $mockAdapter->addResponse($response);
         $stub = new HTTP_Request2(\merigold\przelewy24\src\Przelewy24Component::TEST_URL, HTTP_Request2::METHOD_POST);
         $stub->setAdapter($mockAdapter);
         return $stub;
     });
 }
Example #8
0
 /**
  * Returns the next response from the queue built by addResponse()
  *
  * If the queue is empty it will return default empty response with status 400,
  * if an Exception object was added to the queue it will be thrown.
  *
  * @param    HTTP_Request2
  * @return   HTTP_Request2_Response
  * @throws   Exception
  */
 public function sendRequest(HTTP_Request2 $request)
 {
     $environment = base64_encode(serialize($this->buildEnvironment($request)));
     $file = $request->getConfig('index_file');
     $dir = PHPCLIHTTP_FILEPATH_BASE;
     $command = "{$dir}/sendrequest.php {$file} {$environment}";
     exec($command, $output, $return_var);
     if ($return_var !== 0) {
         die("Something went wrong with the request.");
     }
     $output_as_string = trim(implode("\n", $output));
     $output_base64_decoded = base64_decode($output_as_string);
     $output_unserialized = unserialize($output_base64_decoded);
     $response = new HTTP_Request2_Response("HTTP/1.1 200 OK\r\n");
     $response->appendBody($output_unserialized['html']);
     return $response;
 }
 public function testShouldFailGracefullyOnFailedTransaction()
 {
     $response = new HTTP_Request2_Response('HTTP/1.1 200 OK');
     $response->appendBody(file_get_contents(dirname(__FILE__) . '/data/AuthorizeNet/error.html'));
     $mock = new HTTP_Request2_Adapter_Mock();
     $mock->addResponse($response);
     $request = new HTTP_Request2();
     $request->setAdapter($mock);
     $object = Payment_Process2::factory('AuthorizeNet');
     $object->login = '******';
     $object->password = '******';
     $object->amount = 1;
     $object->action = Payment_Process2::ACTION_NORMAL;
     $object->setRequest($request);
     $object->setPayment($this->aValidPayment());
     $result = $object->process();
     $this->assertTrue($result instanceof PEAR_Error);
 }
Example #10
0
 /**
  * Creates a array of responses from the batch response body.
  * 
  * @param string            $body           The HTTP response body.
  * @param IMimeReaderWriter $mimeSerializer The MIME reader and writer.
  * 
  * @return array
  */
 private static function _constructResponses($body, $mimeSerializer)
 {
     $responses = array();
     $parts = $mimeSerializer->decodeMimeMultipart($body);
     // Decrease the count of parts to remove the batch response body and just
     // include change sets response body. We may need to undo this action in
     // case that batch response body has useful info.
     $count = count($parts) - 1;
     for ($i = 0; $i < $count; $i++) {
         $lines = explode("\r\n", $parts[$i]);
         $response = new \HTTP_Request2_Response($lines[0]);
         $j = 1;
         do {
             $headerLine = $lines[$j++];
             $response->parseHeaderLine($headerLine);
         } while (Resources::EMPTY_STRING != $headerLine);
         $body = implode("\r\n", array_slice($lines, $j));
         $response->appendBody($body);
         $responses[] = $response;
     }
     return $responses;
 }
 /**
  * Constructor
  *
  * @param string                                         $content Http response
  * as string
  *
  * @param WindowsAzure\Common\Internal\Http\BatchRequest $request Source batch
  * request object
  */
 public function __construct($content, $request = null)
 {
     $params['include_bodies'] = true;
     $params['input'] = $content;
     $mimeDecoder = new \Mail_mimeDecode($content);
     $structure = $mimeDecoder->decode($params);
     $parts = $structure->parts;
     $this->_contexts = array();
     $requestContexts = null;
     if ($request != null) {
         Validate::isA($request, 'WindowsAzure\\Common\\Internal\\Http\\BatchRequest', 'request');
         $requestContexts = $request->getContexts();
     }
     $i = 0;
     foreach ($parts as $part) {
         if (!empty($part->body)) {
             $headerEndPos = strpos($part->body, "\r\n\r\n");
             $header = substr($part->body, 0, $headerEndPos);
             $body = substr($part->body, $headerEndPos + 4);
             $headerStrings = explode("\r\n", $header);
             $response = new \HTTP_Request2_Response(array_shift($headerStrings));
             foreach ($headerStrings as $headerString) {
                 $response->parseHeaderLine($headerString);
             }
             $response->appendBody($body);
             $this->_contexts[] = $response;
             if (is_array($requestContexts)) {
                 $expectedCodes = $requestContexts[$i]->getStatusCodes();
                 $statusCode = $response->getStatus();
                 if (!in_array($statusCode, $expectedCodes)) {
                     $reason = $response->getReasonPhrase();
                     throw new ServiceException($statusCode, $reason, $body);
                 }
             }
             $i++;
         }
     }
 }
Example #12
0
 protected function readResponseFromFile($filename)
 {
     $fp = fopen(dirname(dirname(__FILE__)) . '/_files/' . $filename, 'rb');
     $response = new HTTP_Request2_Response(fgets($fp));
     do {
         $headerLine = fgets($fp);
         $response->parseHeaderLine($headerLine);
     } while ('' != trim($headerLine));
     while (!feof($fp)) {
         $response->appendBody(fread($fp, 1024));
     }
     return $response;
 }
Example #13
0
 /**
  * Creates a new HTTP_Request2_Response object from a file
  *
  * @param    resource    file pointer returned by fopen()
  * @return   HTTP_Request2_Response
  * @throws   HTTP_Request2_Exception
  */
 public static function createResponseFromFile($fp)
 {
     $response = new HTTP_Request2_Response(fgets($fp));
     do {
         $headerLine = fgets($fp);
         $response->parseHeaderLine($headerLine);
     } while ('' != trim($headerLine));
     while (!feof($fp)) {
         $response->appendBody(fread($fp, 8192));
     }
     return $response;
 }
    /**
     * Tests validating a fragment of html
     *
     * @return void
     */
    public function testValidateFragment()
    {
        $response = new HTTP_Request2_Response('HTTP/1.1 200 OK');
        $response->appendBody(file_get_contents(dirname(__FILE__) . '/data/ValidateFragment.xml'));
        $this->mock->addResponse($response);
        $v = $this->validator;
        $r = $v->validateFragment('ul.man-side_top,
ul.man-side_up,
ul.man-side_download {
    margin-top: 0.5e;
    margin-bottom: 0.5em;
    margin-left: 0.7em;
    padding-left: 0.7em;
}');
        $this->assertEquals(get_class($r), 'Services_W3C_CSSValidator_Response');
        $this->assertFalse($r->isValid());
        $this->assertEquals($r->uri, 'file://localhost/TextArea');
    }
Example #15
0
 protected function addHttpResponse($body, $status = 'HTTP/1.1 200 OK')
 {
     $response = new HTTP_Request2_Response($status);
     $response->appendBody($body);
     $this->mock->addResponse($response);
 }
 /**
  * Tests {@link SolrConnection::testfetchServerInfo()}.
  */
 function testFetchServerInfo()
 {
     $response = new HTTP_Request2_Response('HTTP/1.0 200 OK');
     $response->appendBody('{"responseHeader":{"status":0,"QTime":10},"lucene":{"solr-spec-version":"1.2.2008.03.21.05.21.15","solr-impl-version":"1.2.0 - buildd - 2008-03-21 05:21:15","lucene-spec-version":"2.3.2","lucene-impl-version":"2.3.2 ${svnversion} - buildd - 2008-09-26 01:53:33"}}');
     $this->httpClientMock->expects($this->once())->method('sendRequest')->with($this->equalTo('/admin/system/?wt=json'))->will($this->returnValue($response));
     $this->assertEquals('1.2.2008.03.21.05.21.15', $this->solr->getSolrSpecVersion());
     $this->assertTrue(version_compare($this->solr->getSolrSpecVersion(), '1.3', '<'));
     $this->assertTrue(version_compare($this->solr->getSolrSpecVersion(), '1.2', '>='));
     $this->assertFalse(version_compare($this->solr->getSolrSpecVersion(), '1.1', '<'));
     $this->assertFalse(version_compare($this->solr->getSolrSpecVersion(), '1.3', '>='));
 }
Example #17
0
 public function setHTTPResponse($expectedResponse, $status = 'HTTP/1.1 200 OK')
 {
     $response = new HTTP_Request2_Response($status);
     $response->appendBody($expectedResponse);
     $this->adapter->addResponse($response);
 }