Esempio n. 1
0
File: util.py Progetto: bboe/betamax
def serialize_response(response, preserve_exact_body_bytes):
    body = {'encoding': response.encoding}
    add_body(response, preserve_exact_body_bytes, body)
    header_map = HTTPHeaderDict(response.raw.headers)
    headers = {}
    for header_name in header_map.keys():
        headers[header_name] = header_map.getlist(header_name)

    return {
        'body': body,
        'headers': headers,
        'status': {'code': response.status_code, 'message': response.reason},
        'url': response.url,
    }
Esempio n. 2
0
def serialize_response(response, preserve_exact_body_bytes):
    body = {'encoding': response.encoding}
    add_body(response, preserve_exact_body_bytes, body)
    header_map = HTTPHeaderDict(response.raw.headers)
    headers = {}
    for header_name in header_map.keys():
        headers[header_name] = header_map.getlist(header_name)

    return {
        'body': body,
        'headers': headers,
        'status': {
            'code': response.status_code,
            'message': response.reason
        },
        'url': response.url,
    }
Esempio n. 3
0
    def route_to_testapp(self, url, requests_req):
        '''This is some tricky stuff.  To test the client methods, we need the
        responses package calls to route to our webtest TestApp WSGI wrapper.
        We use httmock to intercept the requests call, then we handle
        processing in this function instead -- calling the TestApp wrapper.
        '''
        if url.geturl() != requests_req.url:
            logging.warn('%s != %s', url.geturl(), requests_req.url)
        # create a webtest TestRequest from the requests PreparedRequest
        webtest_req = TestRequest.blank(requests_req.url,
                                        method=requests_req.method,
                                        body=requests_req.body,
                                        headers=requests_req.headers)

        # have the TestApp wrapper process the TestRequest
        webtest_resp = self.tasr.request(webtest_req)

        '''webtest responses support multiple headers with the same key, while
        the requests package holds them in a case-insensitive dict of lists of
        (key,value) tuples.  We need to translate by hand here to keep cases
        with multiple headers with the same key
        '''
        headers = HTTPHeaderDict()
        for key, value in webtest_resp.headers.iteritems():
            headers.add(key, value)

        # use the webtest TestResponse to build a new requests HTTPResponse
        requests_http_resp = HTTPResponse(body=webtest_resp.body,
                                           headers=headers,
                                           status=webtest_resp.status_code)

        # get an HTTPAdaptor, then use it to build the requests Response object
        adap = requests.adapters.HTTPAdapter()
        requests_resp = adap.build_response(requests_req, requests_http_resp)

        '''For some reason, we need to explicitly set the _content attribute
        after the response object is built -- it is already in there as
        raw.data, but it doesn't make it to _content, so it never hits
        content() without this intervention.
        '''
        requests_resp._content = webtest_resp.body
        return requests_resp
Esempio n. 4
0
 def test_add_urllib3_response(self):
     r = Response()
     r.status_code = 200
     r.headers = {}
     util.add_urllib3_response(
         {'body': {
             'string': decode('foo'),
             'encoding': 'utf-8'
         }}, r, HTTPHeaderDict())
     assert isinstance(r.raw, urllib3.response.HTTPResponse)
     assert r.content == b'foo'
     assert isinstance(r.raw._original_response, cassette.MockHTTPResponse)
Esempio n. 5
0
File: util.py Progetto: bboe/betamax
def deserialize_response(serialized):
    r = Response()
    r.encoding = serialized['body']['encoding']
    header_dict = HTTPHeaderDict()

    for header_name, header_list in serialized['headers'].items():
        if isinstance(header_list, list):
            for header_value in header_list:
                header_dict.add(header_name, header_value)
        else:
            header_dict.add(header_name, header_list)
    r.headers = CaseInsensitiveDict(header_dict)

    r.url = serialized.get('url', '')
    if 'status' in serialized:
        r.status_code = serialized['status']['code']
        r.reason = serialized['status']['message']
    else:
        r.status_code = serialized['status_code']
        r.reason = _codes[r.status_code][0].upper()
    add_urllib3_response(serialized, r, header_dict)
    return r
Esempio n. 6
0
 def test_serialize_response(self):
     r = Response()
     r.status_code = 200
     r.reason = 'OK'
     r.encoding = 'utf-8'
     r.headers = CaseInsensitiveDict()
     r.url = 'http://example.com'
     util.add_urllib3_response(
         {'body': {
             'string': decode('foo'),
             'encoding': 'utf-8'
         }}, r, HTTPHeaderDict())
     serialized = util.serialize_response(r, False)
     assert serialized is not None
     assert serialized != {}
     assert serialized['body']['encoding'] == 'utf-8'
     assert serialized['body']['string'] == 'foo'
     assert serialized['headers'] == {}
     assert serialized['url'] == 'http://example.com'
     assert serialized['status'] == {'code': 200, 'message': 'OK'}
Esempio n. 7
0
def deserialize_response(serialized):
    r = Response()
    r.encoding = serialized['body']['encoding']
    header_dict = HTTPHeaderDict()

    for header_name, header_list in serialized['headers'].items():
        if isinstance(header_list, list):
            for header_value in header_list:
                header_dict.add(header_name, header_value)
        else:
            header_dict.add(header_name, header_list)
    r.headers = CaseInsensitiveDict(header_dict)

    r.url = serialized.get('url', '')
    if 'status' in serialized:
        r.status_code = serialized['status']['code']
        r.reason = serialized['status']['message']
    else:
        r.status_code = serialized['status_code']
        r.reason = _codes[r.status_code][0].upper()
    add_urllib3_response(serialized, r, header_dict)
    return r
Esempio n. 8
0
 def setUp(self):
     self.resp = mock_response.MockHTTPResponse(
         HTTPHeaderDict({decode('Header'): decode('value')}))
Esempio n. 9
0
    def setUp(self):
        # Make a new serializer to test with
        self.test_serializer = Serializer()
        serializers.serializer_registry['test'] = self.test_serializer

        # Instantiate the cassette to test with
        self.cassette = cassette.Cassette(TestCassette.cassette_name,
                                          'test',
                                          record_mode='once')

        # Create a new object to serialize
        r = Response()
        r.status_code = 200
        r.reason = 'OK'
        r.encoding = 'utf-8'
        r.headers = CaseInsensitiveDict({'Content-Type': decode('foo')})
        r.url = 'http://example.com'
        util.add_urllib3_response(
            {'body': {
                'string': decode('foo'),
                'encoding': 'utf-8'
            }}, r, HTTPHeaderDict({'Content-Type': decode('foo')}))
        self.response = r

        # Create an associated request
        r = Request()
        r.method = 'GET'
        r.url = 'http://example.com'
        r.headers = {}
        r.data = {'key': 'value'}
        self.response.request = r.prepare()
        self.response.request.headers.update(
            {'User-Agent': 'betamax/test header'})

        # Expected serialized cassette data.
        self.json = {
            'request': {
                'body': {
                    'encoding': 'utf-8',
                    'string': 'key=value',
                },
                'headers': {
                    'User-Agent': ['betamax/test header'],
                    'Content-Length': ['9'],
                    'Content-Type': ['application/x-www-form-urlencoded'],
                },
                'method': 'GET',
                'uri': 'http://example.com/',
            },
            'response': {
                'body': {
                    'string': decode('foo'),
                    'encoding': 'utf-8',
                },
                'headers': {
                    'Content-Type': [decode('foo')]
                },
                'status': {
                    'code': 200,
                    'message': 'OK'
                },
                'url': 'http://example.com',
            },
            'recorded_at': '2013-08-31T00:00:00',
        }
        self.date = datetime(2013, 8, 31)
        self.cassette.save_interaction(self.response, self.response.request)
        self.interaction = self.cassette.interactions[0]
    def test_pre_record_hook_v2(self):
        fixtures_path = 'keystoneauth1/tests/unit/data'

        with betamax.Betamax.configure() as config:
            config.before_record(callback=hooks.pre_record_hook)

        cassette = betamax.cassette.Cassette(
            'test_pre_record_hook',
            'json',
            record_mode=None,
            cassette_library_dir=fixtures_path)

        # Create a new object to serialize
        r = models.Response()
        r.status_code = 200
        r.reason = 'OK'
        r.encoding = 'utf-8'
        r.headers = {}
        r.url = 'http://localhost:35357/'

        # load request and response
        with open('%s/keystone_v2_sample_response.json' % fixtures_path) as f:
            response_content = json.loads(f.read())
        with open('%s/keystone_v2_sample_request.json' % fixtures_path) as f:
            request_content = json.loads(f.read())

        body_content = {
            'body': {
                'string': json.dumps(response_content),
                'encoding': 'utf-8',
            }
        }

        betamax.util.add_urllib3_response(
            body_content, r, HTTPHeaderDict({'Accept': 'application/json'}))
        response = r

        # Create an associated request
        r = models.Request()
        r.method = 'GET'
        r.url = 'http://localhost:35357/'
        r.headers = {}
        r.data = {}
        response.request = r.prepare()
        response.request.headers.update({'User-Agent': 'betamax/test header'})

        response.request.body = json.dumps(request_content)

        interaction = cassette.save_interaction(response, response.request)

        # check that all values have been masked
        response_content = json.loads(
            interaction.data['response']['body']['string'])
        self.assertEqual(response_content['access']['token']['expires'],
                         u'9999-12-31T23:59:59Z')
        self.assertEqual(response_content['access']['token']['tenant']['name'],
                         u'dummy')
        self.assertEqual(response_content['access']['user']['name'], u'dummy')

        request_content = json.loads(
            interaction.data['request']['body']['string'])
        self.assertEqual(
            request_content['auth']['passwordCredentials']['password'],
            u'********')
        self.assertEqual(
            request_content['auth']['passwordCredentials']['username'],
            u'dummy')
        self.assertEqual(request_content['auth']['tenantName'], u'dummy')
Esempio n. 11
0
 def _set_raw(self):
     utils.add_urllib3_response(
         {'body': {
             'string': self.html,
             'encoding': 'utf-8'
         }}, self, HTTPHeaderDict(self.headers))