예제 #1
0
 def test_hydrate_from_headers_empty_headers_due_to_filtering(self):
     headers = HTTPHeaderDict()
     headers.add('asasd', 'sdfsdf')
     metadata = MetaData()
     metadata_original = copy.deepcopy(metadata)
     self.assertEqual(str(sorted(metadata_original.__dict__)),
                      str(sorted(self.hydrator.hydrate_from_headers(metadata, headers).__dict__)))
예제 #2
0
    def test_add(self):
        d = HTTPHeaderDict()

        d['A'] = 'foo'
        d.add('a', 'bar')

        self.assertEqual(d['a'], 'foo, bar')
        self.assertEqual(d['A'], 'foo, bar')
예제 #3
0
    def test_filter_system_filtering(self):

        system_headers = self.metadata_http_descriptor.get_all_http_headers()
        headers = HTTPHeaderDict()
        for h in system_headers:
            headers.add(h, h.upper())

        count_system = len(system_headers)
        headers.add('another', 'header')
        self.assertEqual(count_system, len(self.metadata_http_headers_filter.filter_system(headers)))
예제 #4
0
    def test_add_multiple_allowed(self):
        d = HTTPHeaderDict()
        d['Cookie'] = 'foo'
        d.add('cookie', 'bar')

        self.assertEqual(d['cookie'], 'foo, bar')
        self.assertEqual(d['Cookie'], 'foo, bar')

        d.add('cookie', 'asdf')
        self.assertEqual(d['cookie'], 'foo, bar, asdf')
예제 #5
0
 def read_http_start_line_and_headers(payload):
     headers = HTTPHeaderDict()
     start_line = None
     for count, line in enumerate(payload):
         if count == 0:
             start_line = line
         elif line == "\r\n":
             break
         else:
             pos = line.index(":")
             assert pos != -1
             headers.add(line[:pos], line[pos+1:].strip())
     return start_line, headers
예제 #6
0
class TestHTTPHeaderDict(unittest.TestCase):
    def setUp(self):
        self.d = HTTPHeaderDict(A='foo')
        self.d.add('a', 'bar')

    def test_overwriting_with_setitem_replaces(self):
        d = HTTPHeaderDict()

        d['A'] = 'foo'
        self.assertEqual(d['a'], 'foo')

        d['a'] = 'bar'
        self.assertEqual(d['A'], 'bar')

    def test_copy(self):
        h = self.d.copy()
        self.assertTrue(self.d is not h)
        self.assertEqual(self.d, h)

    def test_add(self):
        d = HTTPHeaderDict()

        d['A'] = 'foo'
        d.add('a', 'bar')

        self.assertEqual(d['a'], 'foo, bar')
        self.assertEqual(d['A'], 'foo, bar')

    def test_getlist(self):
        self.assertEqual(self.d.getlist('a'), ['foo', 'bar'])
        self.assertEqual(self.d.getlist('A'), ['foo', 'bar'])
        self.assertEqual(self.d.getlist('b'), [])

    def test_delitem(self):
        del self.d['a']
        self.assertFalse('a' in self.d)
        self.assertFalse('A' in self.d)

    def test_equal(self):
        b = HTTPHeaderDict({'a': 'foo, bar'})
        self.assertEqual(self.d, b)
        c = [('a', 'foo, bar')]
        self.assertNotEqual(self.d, c)

    def test_len(self):
        self.assertEqual(len(self.d), 1)

    def test_repr(self):
        rep = "HTTPHeaderDict({'A': 'foo, bar'})"
        self.assertEqual(repr(self.d), rep)
예제 #7
0
    def test_headerdict(self):
        default_headers = HTTPHeaderDict(a='b')
        proxy_headers = HTTPHeaderDict()
        proxy_headers.add('foo', 'bar')

        http = proxy_from_url(
            self.proxy_url,
            headers=default_headers,
            proxy_headers=proxy_headers)

        request_headers = HTTPHeaderDict(baz='quux')
        r = http.request('GET', '%s/headers' % self.http_url, headers=request_headers)
        returned_headers = json.loads(r.data.decode())
        self.assertEqual(returned_headers.get('Foo'), 'bar')
        self.assertEqual(returned_headers.get('Baz'), 'quux')
    def test_repeating_files(self):
        files = HTTPHeaderDict()
        files.add('fileA', ('a.txt', 'AAA'))
        files.add('f1', ('b.txt', 'BBB'))
        files.add('fileA', ('c.txt', 'CCC'))

        request = _prepare_request(files=files)
        reader = _create_reader(request)
        self._read_body(reader, request)

        self._assert_files(files, reader.files)
예제 #9
0
파일: mocks.py 프로젝트: eloylp/pyddsclient
    def urlopen(self, method, url=None, headers=None, body=None, status=200):

        headers_dict = HTTPHeaderDict()
        headers_dict.add('url', url)
        headers_dict.add('method', method)

        if headers is not None and isinstance(headers, dict):
            for k, v in headers.items():
                headers_dict.add(k, v)

        if body is None:
            body = ''.encode()
        elif isinstance(body, dict):
            body = json.dumps(body).encode()
        else:
            body = body.encode()

        return Bunch(data=body, headers=headers_dict, status=status)
예제 #10
0
 def test_extend_from_dict(self, d: HTTPHeaderDict) -> None:
     d.extend(dict(cookie="asdf"), b="100")
     assert d["cookie"] == "foo, bar, asdf"
     assert d["b"] == "100"
     d.add("cookie", "with, comma")
     assert d.getlist("cookie") == ["foo", "bar", "asdf", "with, comma"]
예제 #11
0
class TestHTTPHeaderDict(unittest.TestCase):
    def setUp(self):
        self.d = HTTPHeaderDict(Cookie='foo')
        self.d.add('cookie', 'bar')

    def test_create_from_kwargs(self):
        h = HTTPHeaderDict(ab=1, cd=2, ef=3, gh=4)
        self.assertEqual(len(h), 4)
        self.assertTrue('ab' in h)

    def test_create_from_dict(self):
        h = HTTPHeaderDict(dict(ab=1, cd=2, ef=3, gh=4))
        self.assertEqual(len(h), 4)
        self.assertTrue('ab' in h)

    def test_create_from_iterator(self):
        teststr = 'urllib3ontherocks'
        h = HTTPHeaderDict((c, c * 5) for c in teststr)
        self.assertEqual(len(h), len(set(teststr)))

    def test_create_from_list(self):
        h = HTTPHeaderDict([('ab', 'A'), ('cd', 'B'), ('cookie', 'C'),
                            ('cookie', 'D'), ('cookie', 'E')])
        self.assertEqual(len(h), 3)
        self.assertTrue('ab' in h)
        clist = h.getlist('cookie')
        self.assertEqual(len(clist), 3)
        self.assertEqual(clist[0], 'C')
        self.assertEqual(clist[-1], 'E')

    def test_create_from_headerdict(self):
        org = HTTPHeaderDict([('ab', 'A'), ('cd', 'B'), ('cookie', 'C'),
                              ('cookie', 'D'), ('cookie', 'E')])
        h = HTTPHeaderDict(org)
        self.assertEqual(len(h), 3)
        self.assertTrue('ab' in h)
        clist = h.getlist('cookie')
        self.assertEqual(len(clist), 3)
        self.assertEqual(clist[0], 'C')
        self.assertEqual(clist[-1], 'E')
        self.assertFalse(h is org)
        self.assertEqual(h, org)

    def test_setitem(self):
        self.d['Cookie'] = 'foo'
        self.assertEqual(self.d['cookie'], 'foo')
        self.d['cookie'] = 'with, comma'
        self.assertEqual(self.d.getlist('cookie'), ['with, comma'])

    def test_update(self):
        self.d.update(dict(Cookie='foo'))
        self.assertEqual(self.d['cookie'], 'foo')
        self.d.update(dict(cookie='with, comma'))
        self.assertEqual(self.d.getlist('cookie'), ['with, comma'])

    def test_delitem(self):
        del self.d['cookie']
        self.assertFalse('cookie' in self.d)
        self.assertFalse('COOKIE' in self.d)

    def test_add_well_known_multiheader(self):
        self.d.add('COOKIE', 'asdf')
        self.assertEqual(self.d.getlist('cookie'), ['foo', 'bar', 'asdf'])
        self.assertEqual(self.d['cookie'], 'foo, bar, asdf')

    def test_add_comma_separated_multiheader(self):
        self.d.add('bar', 'foo')
        self.d.add('BAR', 'bar')
        self.d.add('Bar', 'asdf')
        self.assertEqual(self.d.getlist('bar'), ['foo', 'bar', 'asdf'])
        self.assertEqual(self.d['bar'], 'foo, bar, asdf')

    def test_extend_from_list(self):
        self.d.extend([('set-cookie', '100'), ('set-cookie', '200'),
                       ('set-cookie', '300')])
        self.assertEqual(self.d['set-cookie'], '100, 200, 300')

    def test_extend_from_dict(self):
        self.d.extend(dict(cookie='asdf'), b='100')
        self.assertEqual(self.d['cookie'], 'foo, bar, asdf')
        self.assertEqual(self.d['b'], '100')
        self.d.add('cookie', 'with, comma')
        self.assertEqual(self.d.getlist('cookie'),
                         ['foo', 'bar', 'asdf', 'with, comma'])

    def test_extend_from_container(self):
        h = NonMappingHeaderContainer(Cookie='foo', e='foofoo')
        self.d.extend(h)
        self.assertEqual(self.d['cookie'], 'foo, bar, foo')
        self.assertEqual(self.d['e'], 'foofoo')
        self.assertEqual(len(self.d), 2)

    def test_extend_from_headerdict(self):
        h = HTTPHeaderDict(Cookie='foo', e='foofoo')
        self.d.extend(h)
        self.assertEqual(self.d['cookie'], 'foo, bar, foo')
        self.assertEqual(self.d['e'], 'foofoo')
        self.assertEqual(len(self.d), 2)

    def test_copy(self):
        h = self.d.copy()
        self.assertTrue(self.d is not h)
        self.assertEqual(self.d, h)

    def test_getlist(self):
        self.assertEqual(self.d.getlist('cookie'), ['foo', 'bar'])
        self.assertEqual(self.d.getlist('Cookie'), ['foo', 'bar'])
        self.assertEqual(self.d.getlist('b'), [])
        self.d.add('b', 'asdf')
        self.assertEqual(self.d.getlist('b'), ['asdf'])

    def test_getlist_after_copy(self):
        self.assertEqual(self.d.getlist('cookie'),
                         HTTPHeaderDict(self.d).getlist('cookie'))

    def test_equal(self):
        b = HTTPHeaderDict(cookie='foo, bar')
        c = NonMappingHeaderContainer(cookie='foo, bar')
        self.assertEqual(self.d, b)
        self.assertEqual(self.d, c)
        self.assertNotEqual(self.d, 2)

    def test_not_equal(self):
        b = HTTPHeaderDict(cookie='foo, bar')
        c = NonMappingHeaderContainer(cookie='foo, bar')
        self.assertFalse(self.d != b)
        self.assertFalse(self.d != c)
        self.assertNotEqual(self.d, 2)

    def test_pop(self):
        key = 'Cookie'
        a = self.d[key]
        b = self.d.pop(key)
        self.assertEqual(a, b)
        self.assertFalse(key in self.d)
        self.assertRaises(KeyError, self.d.pop, key)
        dummy = object()
        self.assertTrue(dummy is self.d.pop(key, dummy))

    def test_discard(self):
        self.d.discard('cookie')
        self.assertFalse('cookie' in self.d)
        self.d.discard('cookie')

    def test_len(self):
        self.assertEqual(len(self.d), 1)
        self.d.add('cookie', 'bla')
        self.d.add('asdf', 'foo')
        # len determined by unique fieldnames
        self.assertEqual(len(self.d), 2)

    def test_repr(self):
        rep = "HTTPHeaderDict({'Cookie': 'foo, bar'})"
        self.assertEqual(repr(self.d), rep)

    def test_items(self):
        items = self.d.items()
        self.assertEqual(len(items), 2)
        self.assertEqual(items[0][0], 'Cookie')
        self.assertEqual(items[0][1], 'foo')
        self.assertEqual(items[1][0], 'Cookie')
        self.assertEqual(items[1][1], 'bar')

    def test_dict_conversion(self):
        # Also tested in connectionpool, needs to preserve case
        hdict = {
            'Content-Length': '0',
            'Content-type': 'text/plain',
            'Server': 'TornadoServer/1.2.3'
        }
        h = dict(HTTPHeaderDict(hdict).items())
        self.assertEqual(hdict, h)

    def test_string_enforcement(self):
        # This currently throws AttributeError on key.lower(), should probably be something nicer
        self.assertRaises(Exception, self.d.__setitem__, 3, 5)
        self.assertRaises(Exception, self.d.add, 3, 4)
        self.assertRaises(Exception, self.d.__delitem__, 3)
        self.assertRaises(Exception, HTTPHeaderDict, {3: 3})

    def test_from_httplib_py2(self):
        if six.PY3:
            raise SkipTest(
                "python3 has a different internal header implementation")
        msg = """
Server: nginx
Content-Type: text/html; charset=windows-1251
Connection: keep-alive
X-Some-Multiline: asdf
 asdf
 asdf
Set-Cookie: bb_lastvisit=1348253375; expires=Sat, 21-Sep-2013 18:49:35 GMT; path=/
Set-Cookie: bb_lastactivity=0; expires=Sat, 21-Sep-2013 18:49:35 GMT; path=/
www-authenticate: asdf
www-authenticate: bla

"""
        buffer = six.moves.StringIO(msg.lstrip().replace('\n', '\r\n'))
        msg = six.moves.http_client.HTTPMessage(buffer)
        d = HTTPHeaderDict.from_httplib(msg)
        self.assertEqual(d['server'], 'nginx')
        cookies = d.getlist('set-cookie')
        self.assertEqual(len(cookies), 2)
        self.assertTrue(cookies[0].startswith("bb_lastvisit"))
        self.assertTrue(cookies[1].startswith("bb_lastactivity"))
        self.assertEqual(d['x-some-multiline'].split(),
                         ['asdf', 'asdf', 'asdf'])
        self.assertEqual(d['www-authenticate'], 'asdf, bla')
        self.assertEqual(d.getlist('www-authenticate'), ['asdf', 'bla'])
예제 #12
0
    def test_repeating_value(self):
        data = HTTPHeaderDict()
        data.add('p1', 'abc')
        data.add('x', 'def')
        data.add('p1', 'x')
        data.add('x', '-1239-')
        data.add('x', '!@#$%^&*()_+')
        data.add('x', '.')
        data.add('another_param', '987654321')

        request = _prepare_request(data=data)

        reader = _create_reader(request)
        self._read_body(reader, request)

        self.assertEqual({
            'p1': ['abc', 'x'],
            'x': ['def', '-1239-', '!@#$%^&*()_+', '.'],
            'another_param': '987654321'
        }, reader.values)
        self.assertEqual({}, reader.files)
예제 #13
0
    def update_user(
        self: api_client.Api,
        body: typing.Union[SchemaForRequestBodyApplicationJson],
        path_params: RequestPathParams = frozendict(),
        content_type: str = 'application/json',
        stream: bool = False,
        timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None,
        skip_deserialization: bool = False,
    ) -> typing.Union[
        api_client.ApiResponseWithoutDeserialization
    ]:
        """
        Updated user
        :param skip_deserialization: If true then api_response.response will be set but
            api_response.body and api_response.headers will not be deserialized into schema
            class instances
        """
        self._verify_typed_dict_inputs(RequestPathParams, path_params)

        _path_params = {}
        for parameter in (
            request_path_username,
        ):
            parameter_data = path_params.get(parameter.name, unset)
            if parameter_data is unset:
                continue
            serialized_data = parameter.serialize(parameter_data)
            _path_params.update(serialized_data)

        _headers = HTTPHeaderDict()
        # TODO add cookie handling

        if body is unset:
            raise exceptions.ApiValueError(
                'The required body parameter has an invalid value of: unset. Set a valid value instead')
        _fields = None
        _body = None
        serialized_data = request_body_user.serialize(body, content_type)
        _headers.add('Content-Type', content_type)
        if 'fields' in serialized_data:
            _fields = serialized_data['fields']
        elif 'body' in serialized_data:
            _body = serialized_data['body']
        response = self.api_client.call_api(
            resource_path=_path,
            method=_method,
            path_params=_path_params,
            headers=_headers,
            fields=_fields,
            body=_body,
            stream=stream,
            timeout=timeout,
        )

        if skip_deserialization:
            api_response = api_client.ApiResponseWithoutDeserialization(response=response)
        else:
            response_for_status = _status_code_to_response.get(str(response.status))
            if response_for_status:
                api_response = response_for_status.deserialize(response, self.api_client.configuration)
            else:
                api_response = api_client.ApiResponseWithoutDeserialization(response=response)

        if not 200 <= response.status <= 299:
            raise exceptions.ApiException(api_response=api_response)

        return api_response
예제 #14
0
def d():
    header_dict = HTTPHeaderDict(Cookie='foo')
    header_dict.add('cookie', 'bar')
    return header_dict
예제 #15
0
 def test_getlist(self, d: HTTPHeaderDict) -> None:
     assert d.getlist("cookie") == ["foo", "bar"]
     assert d.getlist("Cookie") == ["foo", "bar"]
     assert d.getlist("b") == []
     d.add("b", "asdf")
     assert d.getlist("b") == ["asdf"]
    def create_users_with_array_input(
        self: api_client.Api,
        body: typing.Union[SchemaForRequestBodyApplicationJson],
        content_type: str = 'application/json',
        stream: bool = False,
        timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None,
        skip_deserialization: bool = False,
    ) -> typing.Union[ApiResponseForDefault,
                      api_client.ApiResponseWithoutDeserialization]:
        """
        Creates list of users with given input array
        :param skip_deserialization: If true then api_response.response will be set but
            api_response.body and api_response.headers will not be deserialized into schema
            class instances
        """

        _headers = HTTPHeaderDict()
        # TODO add cookie handling

        if body is unset:
            raise exceptions.ApiValueError(
                'The required body parameter has an invalid value of: unset. Set a valid value instead'
            )
        _fields = None
        _body = None
        serialized_data = request_body_user.serialize(body, content_type)
        _headers.add('Content-Type', content_type)
        if 'fields' in serialized_data:
            _fields = serialized_data['fields']
        elif 'body' in serialized_data:
            _body = serialized_data['body']
        response = self.api_client.call_api(
            resource_path=_path,
            method=_method,
            headers=_headers,
            fields=_fields,
            body=_body,
            stream=stream,
            timeout=timeout,
        )

        if skip_deserialization:
            api_response = api_client.ApiResponseWithoutDeserialization(
                response=response)
        else:
            response_for_status = _status_code_to_response.get(
                str(response.status))
            if response_for_status:
                api_response = response_for_status.deserialize(
                    response, self.api_client.configuration)
            else:
                default_response = _status_code_to_response.get('default')
                if default_response:
                    api_response = default_response.deserialize(
                        response, self.api_client.configuration)
                else:
                    api_response = api_client.ApiResponseWithoutDeserialization(
                        response=response)

        if not 200 <= response.status <= 299:
            raise exceptions.ApiException(api_response=api_response)

        return api_response
    def test_repeating_value(self):
        data = HTTPHeaderDict()
        data.add('p1', 'abc')
        data.add('x', 'def')
        data.add('p1', 'x')
        data.add('x', '-1239-')
        data.add('x', '!@#$%^&*()_+')
        data.add('x', '.')
        data.add('another_param', '987654321')

        request = _prepare_request(data=data)

        reader = _create_reader(request)
        self._read_body(reader, request)

        self.assertEqual(
            {
                'p1': ['abc', 'x'],
                'x': ['def', '-1239-', '!@#$%^&*()_+', '.'],
                'another_param': '987654321'
            }, reader.values)
        self.assertEqual({}, reader.files)
    def parameter_collisions(
        self: api_client.Api,
        body: typing.Union[SchemaForRequestBodyApplicationJson, Unset] = unset,
        query_params: RequestQueryParams = frozendict(),
        header_params: RequestHeaderParams = frozendict(),
        path_params: RequestPathParams = frozendict(),
        cookie_params: RequestCookieParams = frozendict(),
        content_type: str = 'application/json',
        accept_content_types: typing.Tuple[str] = _all_accept_content_types,
        stream: bool = False,
        timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None,
        skip_deserialization: bool = False,
    ) -> typing.Union[ApiResponseFor200,
                      api_client.ApiResponseWithoutDeserialization]:
        """
        parameter collision case
        :param skip_deserialization: If true then api_response.response will be set but
            api_response.body and api_response.headers will not be deserialized into schema
            class instances
        """
        self._verify_typed_dict_inputs(RequestQueryParams, query_params)
        self._verify_typed_dict_inputs(RequestHeaderParams, header_params)
        self._verify_typed_dict_inputs(RequestPathParams, path_params)
        self._verify_typed_dict_inputs(RequestCookieParams, cookie_params)

        _path_params = {}
        for parameter in (
                request_path__3,
                request_path_a_b5,
                request_path_ab2,
                request_path__self3,
                request_path_a_b6,
        ):
            parameter_data = path_params.get(parameter.name, unset)
            if parameter_data is unset:
                continue
            serialized_data = parameter.serialize(parameter_data)
            _path_params.update(serialized_data)

        _query_params = []
        for parameter in (
                request_query__1,
                request_query_a_b,
                request_query_ab,
                request_query__self,
                request_query_a_b2,
        ):
            parameter_data = query_params.get(parameter.name, unset)
            if parameter_data is unset:
                continue
            serialized_data = parameter.serialize(parameter_data)
            _query_params.extend(serialized_data)

        _headers = HTTPHeaderDict()
        for parameter in (
                request_header__2,
                request_header_a_b3,
                request_header__self2,
                request_header_a_b4,
        ):
            parameter_data = header_params.get(parameter.name, unset)
            if parameter_data is unset:
                continue
            serialized_data = parameter.serialize(parameter_data)
            _headers.extend(serialized_data)
        # TODO add cookie handling
        if accept_content_types:
            for accept_content_type in accept_content_types:
                _headers.add('Accept', accept_content_type)

        _fields = None
        _body = None
        if body is not unset:
            serialized_data = request_body_body.serialize(body, content_type)
            _headers.add('Content-Type', content_type)
            if 'fields' in serialized_data:
                _fields = serialized_data['fields']
            elif 'body' in serialized_data:
                _body = serialized_data['body']
        response = self.api_client.call_api(
            resource_path=_path,
            method=_method,
            path_params=_path_params,
            query_params=tuple(_query_params),
            headers=_headers,
            fields=_fields,
            body=_body,
            stream=stream,
            timeout=timeout,
        )

        if skip_deserialization:
            api_response = api_client.ApiResponseWithoutDeserialization(
                response=response)
        else:
            response_for_status = _status_code_to_response.get(
                str(response.status))
            if response_for_status:
                api_response = response_for_status.deserialize(
                    response, self.api_client.configuration)
            else:
                api_response = api_client.ApiResponseWithoutDeserialization(
                    response=response)

        if not 200 <= response.status <= 299:
            raise exceptions.ApiException(api_response=api_response)

        return api_response
def d():
    header_dict = HTTPHeaderDict(Cookie="foo")
    header_dict.add("cookie", "bar")
    return header_dict
예제 #20
0
from natas_utility import *
import html
from urllib3._collections import HTTPHeaderDict

current_level = 30
credentials = get_credentials(current_level)

base_url = 'http://{}.natas.labs.overthewire.org'.format(
    credentials['username'])
auth = (credentials['username'], credentials['password'])

url = base_url

session = requests.session()

data = HTTPHeaderDict()
data.add('username', 'natas31')
data.add('password', '"a" or username = username')
data.add('password', '5')

response = session.post(url, data=data, auth=auth)

content = html.unescape(response.content.decode('utf-8')).replace(
    '<br />', '\n').replace('<br>', '\n')

password_regex = re.compile(r'natas31(.+)<div')
next_password = password_regex.findall(content)[0]
print(next_password)

save_credentials(current_level + 1, next_password)
예제 #21
0
 def test_hydrate_return_object(self):
     headers = HTTPHeaderDict()
     headers.add('asasd', 'sdfsdf')
     self.assertIsInstance(self.hydrator.hydrate_from_headers(MetaData(), headers), MetaData)
예제 #22
0
 def test_filter_http_return_type(self):
     headers = HTTPHeaderDict()
     headers.add('header', 'asda')
     self.assertIsInstance(self.metadata_http_headers_filter.filter_http(headers), HTTPHeaderDict)
예제 #23
0
    def add_pet(
        self: api_client.Api,
        body: typing.Union[SchemaForRequestBodyApplicationJson,
                           SchemaForRequestBodyApplicationXml],
        content_type: str = 'application/json',
        host_index: typing.Optional[int] = None,
        stream: bool = False,
        timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None,
        skip_deserialization: bool = False,
    ) -> typing.Union[ApiResponseFor200,
                      api_client.ApiResponseWithoutDeserialization]:
        """
        Add a new pet to the store
        :param skip_deserialization: If true then api_response.response will be set but
            api_response.body and api_response.headers will not be deserialized into schema
            class instances
        """

        _headers = HTTPHeaderDict()
        # TODO add cookie handling

        if body is unset:
            raise exceptions.ApiValueError(
                'The required body parameter has an invalid value of: unset. Set a valid value instead'
            )
        _fields = None
        _body = None
        serialized_data = request_body_pet.serialize(body, content_type)
        _headers.add('Content-Type', content_type)
        if 'fields' in serialized_data:
            _fields = serialized_data['fields']
        elif 'body' in serialized_data:
            _body = serialized_data['body']
        host = self.get_host('add_pet', _servers, host_index)

        response = self.api_client.call_api(
            resource_path=_path,
            method=_method,
            headers=_headers,
            fields=_fields,
            body=_body,
            auth_settings=_auth,
            host=host,
            stream=stream,
            timeout=timeout,
        )

        if skip_deserialization:
            api_response = api_client.ApiResponseWithoutDeserialization(
                response=response)
        else:
            response_for_status = _status_code_to_response.get(
                str(response.status))
            if response_for_status:
                api_response = response_for_status.deserialize(
                    response, self.api_client.configuration)
            else:
                api_response = api_client.ApiResponseWithoutDeserialization(
                    response=response)

        if not 200 <= response.status <= 299:
            raise exceptions.ApiException(api_response=api_response)

        return api_response
예제 #24
0
 def test_len(self, d: HTTPHeaderDict) -> None:
     assert len(d) == 1
     d.add("cookie", "bla")
     d.add("asdf", "foo")
     # len determined by unique fieldnames
     assert len(d) == 2
예제 #25
0
    def upload_image(
        self: api_client.Api,
        body: typing.Union[SchemaForRequestBodyMultipartFormData, Unset] = unset,
        path_params: RequestPathParams = frozendict(),
        content_type: str = 'multipart/form-data',
        accept_content_types: typing.Tuple[str] = _all_accept_content_types,
        stream: bool = False,
        timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None,
        skip_deserialization: bool = False,
    ) -> typing.Union[
        ApiResponseFor200,
        api_client.ApiResponseWithoutDeserialization
    ]:
        """
        uploads an image
        :param skip_deserialization: If true then api_response.response will be set but
            api_response.body and api_response.headers will not be deserialized into schema
            class instances
        """
        self._verify_typed_dict_inputs(RequestPathParams, path_params)

        _path_params = {}
        for parameter in (
            request_path_pet_id,
        ):
            parameter_data = path_params.get(parameter.name, unset)
            if parameter_data is unset:
                continue
            serialized_data = parameter.serialize(parameter_data)
            _path_params.update(serialized_data)

        _headers = HTTPHeaderDict()
        # TODO add cookie handling
        if accept_content_types:
            for accept_content_type in accept_content_types:
                _headers.add('Accept', accept_content_type)

        _fields = None
        _body = None
        if body is not unset:
            serialized_data = request_body_body.serialize(body, content_type)
            _headers.add('Content-Type', content_type)
            if 'fields' in serialized_data:
                _fields = serialized_data['fields']
            elif 'body' in serialized_data:
                _body = serialized_data['body']
        response = self.api_client.call_api(
            resource_path=_path,
            method=_method,
            path_params=_path_params,
            headers=_headers,
            fields=_fields,
            body=_body,
            auth_settings=_auth,
            stream=stream,
            timeout=timeout,
        )

        if skip_deserialization:
            api_response = api_client.ApiResponseWithoutDeserialization(response=response)
        else:
            response_for_status = _status_code_to_response.get(str(response.status))
            if response_for_status:
                api_response = response_for_status.deserialize(response, self.api_client.configuration)
            else:
                api_response = api_client.ApiResponseWithoutDeserialization(response=response)

        if not 200 <= response.status <= 299:
            raise exceptions.ApiException(api_response=api_response)

        return api_response
예제 #26
0
    def inline_composition(
        self: api_client.Api,
        body: typing.Union[SchemaForRequestBodyApplicationJson,
                           SchemaForRequestBodyMultipartFormData,
                           Unset] = unset,
        query_params: RequestQueryParams = frozendict(),
        content_type: str = 'application/json',
        accept_content_types: typing.Tuple[str] = _all_accept_content_types,
        stream: bool = False,
        timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None,
        skip_deserialization: bool = False,
    ) -> typing.Union[ApiResponseFor200,
                      api_client.ApiResponseWithoutDeserialization]:
        """
        testing composed schemas at inline locations
        :param skip_deserialization: If true then api_response.response will be set but
            api_response.body and api_response.headers will not be deserialized into schema
            class instances
        """
        self._verify_typed_dict_inputs(RequestQueryParams, query_params)

        _query_params = []
        for parameter in (
                request_query_composition_at_root,
                request_query_composition_in_property,
        ):
            parameter_data = query_params.get(parameter.name, unset)
            if parameter_data is unset:
                continue
            serialized_data = parameter.serialize(parameter_data)
            _query_params.extend(serialized_data)

        _headers = HTTPHeaderDict()
        # TODO add cookie handling
        if accept_content_types:
            for accept_content_type in accept_content_types:
                _headers.add('Accept', accept_content_type)

        _fields = None
        _body = None
        if body is not unset:
            serialized_data = request_body_any_type.serialize(
                body, content_type)
            _headers.add('Content-Type', content_type)
            if 'fields' in serialized_data:
                _fields = serialized_data['fields']
            elif 'body' in serialized_data:
                _body = serialized_data['body']
        response = self.api_client.call_api(
            resource_path=_path,
            method=_method,
            query_params=tuple(_query_params),
            headers=_headers,
            fields=_fields,
            body=_body,
            stream=stream,
            timeout=timeout,
        )

        if skip_deserialization:
            api_response = api_client.ApiResponseWithoutDeserialization(
                response=response)
        else:
            response_for_status = _status_code_to_response.get(
                str(response.status))
            if response_for_status:
                api_response = response_for_status.deserialize(
                    response, self.api_client.configuration)
            else:
                api_response = api_client.ApiResponseWithoutDeserialization(
                    response=response)

        if not 200 <= response.status <= 299:
            raise exceptions.ApiException(api_response=api_response)

        return api_response
예제 #27
0
class TestHTTPHeaderDict(unittest.TestCase):
    def setUp(self):
        self.d = HTTPHeaderDict(Cookie='foo')
        self.d.add('cookie', 'bar')

    def test_overwriting_with_setitem_replaces(self):
        d = HTTPHeaderDict()

        d['Cookie'] = 'foo'
        self.assertEqual(d['cookie'], 'foo')

        d['cookie'] = 'bar'
        self.assertEqual(d['Cookie'], 'bar')

    def test_copy(self):
        h = self.d.copy()
        self.assertTrue(self.d is not h)
        self.assertEqual(self.d, h)

    def test_add_multiple_allowed(self):
        d = HTTPHeaderDict()
        d['Cookie'] = 'foo'
        d.add('cookie', 'bar')

        self.assertEqual(d['cookie'], 'foo, bar')
        self.assertEqual(d['Cookie'], 'foo, bar')

        d.add('cookie', 'asdf')
        self.assertEqual(d['cookie'], 'foo, bar, asdf')

    def test_add_multiple_not_allowed(self):
        self.d.add('notmulti', 'should be overwritten on next add call')
        self.d.add('notmulti', 'new val')
        self.assertEqual(self.d['notmulti'], 'new val')
        
    def test_extend(self):
        self.d.extend([('set-cookie', '100'), ('set-cookie', '200'), ('set-cookie', '300')])
        self.assertEqual(self.d['set-cookie'], '100, 200, 300')

        self.d.extend(dict(cookie='asdf'), b='100')
        self.assertEqual(self.d['cookie'], 'foo, bar, asdf')
        self.assertEqual(self.d['b'], '100')
        self.d.add('cookie', 'with, comma')
        self.assertEqual(self.d.getlist('cookie'), ['foo', 'bar', 'asdf', 'with, comma'])
        
        header_object = NonMappingHeaderContainer(e='foofoo')
        self.d.extend(header_object)
        self.assertEqual(self.d['e'], 'foofoo')

    def test_getlist(self):
        self.assertEqual(self.d.getlist('cookie'), ['foo', 'bar'])
        self.assertEqual(self.d.getlist('Cookie'), ['foo', 'bar'])
        self.assertEqual(self.d.getlist('b'), [])
        self.d.add('b', 'asdf')
        self.assertEqual(self.d.getlist('b'), ['asdf'])

    def test_update(self):
        self.d.update(dict(cookie='with, comma'))
        self.assertEqual(self.d.getlist('cookie'), ['with, comma'])

    def test_delitem(self):
        del self.d['cookie']
        self.assertFalse('cookie' in self.d)
        self.assertFalse('COOKIE' in self.d)

    def test_equal(self):
        b = HTTPHeaderDict(cookie='foo, bar')
        c = NonMappingHeaderContainer(cookie='foo, bar')
        self.assertEqual(self.d, b)
        self.assertEqual(self.d, c)
        self.assertNotEqual(self.d, 2)

    def test_not_equal(self):
        b = HTTPHeaderDict(cookie='foo, bar')
        c = NonMappingHeaderContainer(cookie='foo, bar')
        self.assertFalse(self.d != b)
        self.assertFalse(self.d != c)
        self.assertNotEqual(self.d, 2)

    def test_pop(self):
        key = 'Cookie'
        a = self.d[key]
        b = self.d.pop(key)
        self.assertEqual(a, b)
        self.assertFalse(key in self.d)
        self.assertRaises(KeyError, self.d.pop, key)
        dummy = object()
        self.assertTrue(dummy is self.d.pop(key, dummy))

    def test_discard(self):
        self.d.discard('cookie')
        self.assertFalse('cookie' in self.d)
        self.d.discard('cookie')

    def test_len(self):
        self.assertEqual(len(self.d), 1)

    def test_repr(self):
        rep = "HTTPHeaderDict({'Cookie': 'foo, bar'})"
        self.assertEqual(repr(self.d), rep)

    def test_items(self):
        items = self.d.items()
        self.assertEqual(len(items), 2)
        self.assertEqual(items[0][0], 'Cookie')
        self.assertEqual(items[0][1], 'foo')
        self.assertEqual(items[1][0], 'Cookie')
        self.assertEqual(items[1][1], 'bar')

    def test_items_preserving_case(self):
        # Should not be tested only in connectionpool
        HEADERS = {'Content-Length': '0', 'Content-type': 'text/plain',
                    'Server': 'TornadoServer/1.2.3'}
        h = dict(HTTPHeaderDict(HEADERS).items())
        self.assertEqual(HEADERS, h) # to preserve case sensitivity        

    def test_from_httplib(self):
        if six.PY3:
            raise SkipTest()
        from httplib import HTTPMessage
        from StringIO import StringIO

        msg = """
Server: nginx
Content-Type: text/html; charset=windows-1251
Connection: keep-alive
Set-Cookie: bb_lastvisit=1348253375; expires=Sat, 21-Sep-2013 18:49:35 GMT; path=/
Set-Cookie: bb_lastactivity=0; expires=Sat, 21-Sep-2013 18:49:35 GMT; path=/

"""
        msg = HTTPMessage(StringIO(msg.lstrip().replace('\n', '\r\n')))
        d = HTTPHeaderDict.from_httplib(msg)
        self.assertEqual(d['server'], 'nginx')
        cookies = d.getlist('set-cookie')
        self.assertEqual(len(cookies), 2)
        self.assertTrue(cookies[0].startswith("bb_lastvisit"))
        self.assertTrue(cookies[1].startswith("bb_lastactivity"))
예제 #28
0
    def get_pipeline_run_log(
        self: api_client.Api,
        query_params: RequestQueryParams = frozendict(),
        path_params: RequestPathParams = frozendict(),
        accept_content_types: typing.Tuple[str] = _all_accept_content_types,
        stream: bool = False,
        timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None,
        skip_deserialization: bool = False,
    ) -> typing.Union[ApiResponseFor200,
                      api_client.ApiResponseWithoutDeserialization]:
        """
        :param skip_deserialization: If true then api_response.response will be set but
            api_response.body and api_response.headers will not be deserialized into schema
            class instances
        """
        self._verify_typed_dict_inputs(RequestQueryParams, query_params)
        self._verify_typed_dict_inputs(RequestPathParams, path_params)

        _path_params = {}
        for parameter in (
                request_path_organization,
                request_path_pipeline,
                request_path_run,
        ):
            parameter_data = path_params.get(parameter.name, unset)
            if parameter_data is unset:
                continue
            serialized_data = parameter.serialize(parameter_data)
            _path_params.update(serialized_data)

        _query_params = []
        for parameter in (
                request_query_start,
                request_query_download,
        ):
            parameter_data = query_params.get(parameter.name, unset)
            if parameter_data is unset:
                continue
            serialized_data = parameter.serialize(parameter_data)
            _query_params.extend(serialized_data)

        _headers = HTTPHeaderDict()
        # TODO add cookie handling
        if accept_content_types:
            for accept_content_type in accept_content_types:
                _headers.add('Accept', accept_content_type)

        response = self.api_client.call_api(
            resource_path=_path,
            method=_method,
            path_params=_path_params,
            query_params=tuple(_query_params),
            headers=_headers,
            auth_settings=_auth,
            stream=stream,
            timeout=timeout,
        )

        if skip_deserialization:
            api_response = api_client.ApiResponseWithoutDeserialization(
                response=response)
        else:
            response_for_status = _status_code_to_response.get(
                str(response.status))
            if response_for_status:
                api_response = response_for_status.deserialize(
                    response, self.api_client.configuration)
            else:
                api_response = api_client.ApiResponseWithoutDeserialization(
                    response=response)

        if not 200 <= response.status <= 299:
            raise exceptions.ApiException(api_response=api_response)

        return api_response
예제 #29
0
class TestHTTPHeaderDict(unittest.TestCase):
    def setUp(self):
        self.d = HTTPHeaderDict(Cookie="foo")
        self.d.add("cookie", "bar")

    def test_create_from_kwargs(self):
        h = HTTPHeaderDict(ab=1, cd=2, ef=3, gh=4)
        self.assertEqual(len(h), 4)
        self.assertTrue("ab" in h)

    def test_create_from_dict(self):
        h = HTTPHeaderDict(dict(ab=1, cd=2, ef=3, gh=4))
        self.assertEqual(len(h), 4)
        self.assertTrue("ab" in h)

    def test_create_from_iterator(self):
        teststr = "urllib3ontherocks"
        h = HTTPHeaderDict((c, c * 5) for c in teststr)
        self.assertEqual(len(h), len(set(teststr)))

    def test_create_from_list(self):
        h = HTTPHeaderDict([("ab", "A"), ("cd", "B"), ("cookie", "C"), ("cookie", "D"), ("cookie", "E")])
        self.assertEqual(len(h), 3)
        self.assertTrue("ab" in h)
        clist = h.getlist("cookie")
        self.assertEqual(len(clist), 3)
        self.assertEqual(clist[0], "C")
        self.assertEqual(clist[-1], "E")

    def test_create_from_headerdict(self):
        org = HTTPHeaderDict([("ab", "A"), ("cd", "B"), ("cookie", "C"), ("cookie", "D"), ("cookie", "E")])
        h = HTTPHeaderDict(org)
        self.assertEqual(len(h), 3)
        self.assertTrue("ab" in h)
        clist = h.getlist("cookie")
        self.assertEqual(len(clist), 3)
        self.assertEqual(clist[0], "C")
        self.assertEqual(clist[-1], "E")
        self.assertFalse(h is org)
        self.assertEqual(h, org)

    def test_setitem(self):
        self.d["Cookie"] = "foo"
        self.assertEqual(self.d["cookie"], "foo")
        self.d["cookie"] = "with, comma"
        self.assertEqual(self.d.getlist("cookie"), ["with, comma"])

    def test_update(self):
        self.d.update(dict(Cookie="foo"))
        self.assertEqual(self.d["cookie"], "foo")
        self.d.update(dict(cookie="with, comma"))
        self.assertEqual(self.d.getlist("cookie"), ["with, comma"])

    def test_delitem(self):
        del self.d["cookie"]
        self.assertFalse("cookie" in self.d)
        self.assertFalse("COOKIE" in self.d)

    def test_add_well_known_multiheader(self):
        self.d.add("COOKIE", "asdf")
        self.assertEqual(self.d.getlist("cookie"), ["foo", "bar", "asdf"])
        self.assertEqual(self.d["cookie"], "foo, bar, asdf")

    def test_add_comma_separated_multiheader(self):
        self.d.add("bar", "foo")
        self.d.add("BAR", "bar")
        self.d.add("Bar", "asdf")
        self.assertEqual(self.d.getlist("bar"), ["foo", "bar", "asdf"])
        self.assertEqual(self.d["bar"], "foo, bar, asdf")

    def test_extend_from_list(self):
        self.d.extend([("set-cookie", "100"), ("set-cookie", "200"), ("set-cookie", "300")])
        self.assertEqual(self.d["set-cookie"], "100, 200, 300")

    def test_extend_from_dict(self):
        self.d.extend(dict(cookie="asdf"), b="100")
        self.assertEqual(self.d["cookie"], "foo, bar, asdf")
        self.assertEqual(self.d["b"], "100")
        self.d.add("cookie", "with, comma")
        self.assertEqual(self.d.getlist("cookie"), ["foo", "bar", "asdf", "with, comma"])

    def test_extend_from_container(self):
        h = NonMappingHeaderContainer(Cookie="foo", e="foofoo")
        self.d.extend(h)
        self.assertEqual(self.d["cookie"], "foo, bar, foo")
        self.assertEqual(self.d["e"], "foofoo")
        self.assertEqual(len(self.d), 2)

    def test_extend_from_headerdict(self):
        h = HTTPHeaderDict(Cookie="foo", e="foofoo")
        self.d.extend(h)
        self.assertEqual(self.d["cookie"], "foo, bar, foo")
        self.assertEqual(self.d["e"], "foofoo")
        self.assertEqual(len(self.d), 2)

    def test_copy(self):
        h = self.d.copy()
        self.assertTrue(self.d is not h)
        self.assertEqual(self.d, h)

    def test_getlist(self):
        self.assertEqual(self.d.getlist("cookie"), ["foo", "bar"])
        self.assertEqual(self.d.getlist("Cookie"), ["foo", "bar"])
        self.assertEqual(self.d.getlist("b"), [])
        self.d.add("b", "asdf")
        self.assertEqual(self.d.getlist("b"), ["asdf"])

    def test_getlist_after_copy(self):
        self.assertEqual(self.d.getlist("cookie"), HTTPHeaderDict(self.d).getlist("cookie"))

    def test_equal(self):
        b = HTTPHeaderDict(cookie="foo, bar")
        c = NonMappingHeaderContainer(cookie="foo, bar")
        self.assertEqual(self.d, b)
        self.assertEqual(self.d, c)
        self.assertNotEqual(self.d, 2)

    def test_not_equal(self):
        b = HTTPHeaderDict(cookie="foo, bar")
        c = NonMappingHeaderContainer(cookie="foo, bar")
        self.assertFalse(self.d != b)
        self.assertFalse(self.d != c)
        self.assertNotEqual(self.d, 2)

    def test_pop(self):
        key = "Cookie"
        a = self.d[key]
        b = self.d.pop(key)
        self.assertEqual(a, b)
        self.assertFalse(key in self.d)
        self.assertRaises(KeyError, self.d.pop, key)
        dummy = object()
        self.assertTrue(dummy is self.d.pop(key, dummy))

    def test_discard(self):
        self.d.discard("cookie")
        self.assertFalse("cookie" in self.d)
        self.d.discard("cookie")

    def test_len(self):
        self.assertEqual(len(self.d), 1)
        self.d.add("cookie", "bla")
        self.d.add("asdf", "foo")
        # len determined by unique fieldnames
        self.assertEqual(len(self.d), 2)

    def test_repr(self):
        rep = "HTTPHeaderDict({'Cookie': 'foo, bar'})"
        self.assertEqual(repr(self.d), rep)

    def test_items(self):
        items = self.d.items()
        self.assertEqual(len(items), 2)
        self.assertEqual(items[0][0], "Cookie")
        self.assertEqual(items[0][1], "foo")
        self.assertEqual(items[1][0], "Cookie")
        self.assertEqual(items[1][1], "bar")

    def test_dict_conversion(self):
        # Also tested in connectionpool, needs to preserve case
        hdict = {"Content-Length": "0", "Content-type": "text/plain", "Server": "TornadoServer/1.2.3"}
        h = dict(HTTPHeaderDict(hdict).items())
        self.assertEqual(hdict, h)

    def test_string_enforcement(self):
        # This currently throws AttributeError on key.lower(), should probably be something nicer
        self.assertRaises(Exception, self.d.__setitem__, 3, 5)
        self.assertRaises(Exception, self.d.add, 3, 4)
        self.assertRaises(Exception, self.d.__delitem__, 3)
        self.assertRaises(Exception, HTTPHeaderDict, {3: 3})

    def test_from_httplib_py2(self):
        if six.PY3:
            raise SkipTest("python3 has a different internal header implementation")
        msg = """
Server: nginx
Content-Type: text/html; charset=windows-1251
Connection: keep-alive
X-Some-Multiline: asdf
 asdf
 asdf
Set-Cookie: bb_lastvisit=1348253375; expires=Sat, 21-Sep-2013 18:49:35 GMT; path=/
Set-Cookie: bb_lastactivity=0; expires=Sat, 21-Sep-2013 18:49:35 GMT; path=/
www-authenticate: asdf
www-authenticate: bla

"""
        buffer = six.moves.StringIO(msg.lstrip().replace("\n", "\r\n"))
        msg = six.moves.http_client.HTTPMessage(buffer)
        d = HTTPHeaderDict.from_httplib(msg)
        self.assertEqual(d["server"], "nginx")
        cookies = d.getlist("set-cookie")
        self.assertEqual(len(cookies), 2)
        self.assertTrue(cookies[0].startswith("bb_lastvisit"))
        self.assertTrue(cookies[1].startswith("bb_lastactivity"))
        self.assertEqual(d["x-some-multiline"].split(), ["asdf", "asdf", "asdf"])
        self.assertEqual(d["www-authenticate"], "asdf, bla")
        self.assertEqual(d.getlist("www-authenticate"), ["asdf", "bla"])
예제 #30
0
    def upload_download_file(
        self: api_client.Api,
        body: typing.Union[SchemaForRequestBodyApplicationOctetStream],
        content_type: str = 'application/octet-stream',
        accept_content_types: typing.Tuple[str] = _all_accept_content_types,
        stream: bool = False,
        timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None,
        skip_deserialization: bool = False,
    ) -> typing.Union[ApiResponseFor200,
                      api_client.ApiResponseWithoutDeserialization]:
        """
        uploads a file and downloads a file using application/octet-stream
        :param skip_deserialization: If true then api_response.response will be set but
            api_response.body and api_response.headers will not be deserialized into schema
            class instances
        """

        _headers = HTTPHeaderDict()
        # TODO add cookie handling
        if accept_content_types:
            for accept_content_type in accept_content_types:
                _headers.add('Accept', accept_content_type)

        if body is unset:
            raise exceptions.ApiValueError(
                'The required body parameter has an invalid value of: unset. Set a valid value instead'
            )
        _fields = None
        _body = None
        serialized_data = request_body_body.serialize(body, content_type)
        _headers.add('Content-Type', content_type)
        if 'fields' in serialized_data:
            _fields = serialized_data['fields']
        elif 'body' in serialized_data:
            _body = serialized_data['body']
        response = self.api_client.call_api(
            resource_path=_path,
            method=_method,
            headers=_headers,
            fields=_fields,
            body=_body,
            stream=stream,
            timeout=timeout,
        )

        if skip_deserialization:
            api_response = api_client.ApiResponseWithoutDeserialization(
                response=response)
        else:
            response_for_status = _status_code_to_response.get(
                str(response.status))
            if response_for_status:
                api_response = response_for_status.deserialize(
                    response, self.api_client.configuration)
            else:
                api_response = api_client.ApiResponseWithoutDeserialization(
                    response=response)

        if not 200 <= response.status <= 299:
            raise exceptions.ApiException(api_response=api_response)

        return api_response
예제 #31
0
class TestHTTPHeaderDict(unittest.TestCase):
    def setUp(self):
        self.d = HTTPHeaderDict(Cookie='foo')
        self.d.add('cookie', 'bar')

    def test_create_from_kwargs(self):
        h = HTTPHeaderDict(ab=1, cd=2, ef=3, gh=4)
        self.assertEqual(len(h), 4)
        self.assertTrue('ab' in h)
    
    def test_create_from_dict(self):
        h = HTTPHeaderDict(dict(ab=1, cd=2, ef=3, gh=4))
        self.assertEqual(len(h), 4)
        self.assertTrue('ab' in h)
    
    def test_create_from_iterator(self):
        teststr = 'urllib3ontherocks'
        h = HTTPHeaderDict((c, c*5) for c in teststr)
        self.assertEqual(len(h), len(set(teststr)))
        
    def test_create_from_list(self):
        h = HTTPHeaderDict([('ab', 'A'), ('cd', 'B'), ('cookie', 'C'), ('cookie', 'D'), ('cookie', 'E')])
        self.assertEqual(len(h), 3)
        self.assertTrue('ab' in h)
        clist = h.getlist('cookie')
        self.assertEqual(len(clist), 3)
        self.assertEqual(clist[0], 'C')
        self.assertEqual(clist[-1], 'E')

    def test_create_from_headerdict(self):
        org = HTTPHeaderDict([('ab', 'A'), ('cd', 'B'), ('cookie', 'C'), ('cookie', 'D'), ('cookie', 'E')])
        h = HTTPHeaderDict(org)
        self.assertEqual(len(h), 3)
        self.assertTrue('ab' in h)
        clist = h.getlist('cookie')
        self.assertEqual(len(clist), 3)
        self.assertEqual(clist[0], 'C')
        self.assertEqual(clist[-1], 'E')
        self.assertFalse(h is org)
        self.assertEqual(h, org)

    def test_setitem(self):
        self.d['Cookie'] = 'foo'
        self.assertEqual(self.d['cookie'], 'foo')
        self.d['cookie'] = 'with, comma'
        self.assertEqual(self.d.getlist('cookie'), ['with, comma'])

    def test_update(self):
        self.d.update(dict(Cookie='foo'))
        self.assertEqual(self.d['cookie'], 'foo')
        self.d.update(dict(cookie='with, comma'))
        self.assertEqual(self.d.getlist('cookie'), ['with, comma'])

    def test_delitem(self):
        del self.d['cookie']
        self.assertFalse('cookie' in self.d)
        self.assertFalse('COOKIE' in self.d)

    def test_add_well_known_multiheader(self):
        self.d.add('COOKIE', 'asdf')
        self.assertEqual(self.d.getlist('cookie'), ['foo', 'bar', 'asdf'])
        self.assertEqual(self.d['cookie'], 'foo, bar, asdf')

    def test_add_comma_separated_multiheader(self):
        self.d.add('bar', 'foo')
        self.d.add('BAR', 'bar')
        self.d.add('Bar', 'asdf')
        self.assertEqual(self.d.getlist('bar'), ['foo', 'bar', 'asdf'])
        self.assertEqual(self.d['bar'], 'foo, bar, asdf')

    def test_extend_from_list(self):
        self.d.extend([('set-cookie', '100'), ('set-cookie', '200'), ('set-cookie', '300')])
        self.assertEqual(self.d['set-cookie'], '100, 200, 300')

    def test_extend_from_dict(self):
        self.d.extend(dict(cookie='asdf'), b='100')
        self.assertEqual(self.d['cookie'], 'foo, bar, asdf')
        self.assertEqual(self.d['b'], '100')
        self.d.add('cookie', 'with, comma')
        self.assertEqual(self.d.getlist('cookie'), ['foo', 'bar', 'asdf', 'with, comma'])
        
    def test_extend_from_container(self):
        h = NonMappingHeaderContainer(Cookie='foo', e='foofoo')
        self.d.extend(h)
        self.assertEqual(self.d['cookie'], 'foo, bar, foo')
        self.assertEqual(self.d['e'], 'foofoo')
        self.assertEqual(len(self.d), 2)

    def test_extend_from_headerdict(self):
        h = HTTPHeaderDict(Cookie='foo', e='foofoo')
        self.d.extend(h)
        self.assertEqual(self.d['cookie'], 'foo, bar, foo')
        self.assertEqual(self.d['e'], 'foofoo')
        self.assertEqual(len(self.d), 2)

    def test_copy(self):
        h = self.d.copy()
        self.assertTrue(self.d is not h)
        self.assertEqual(self.d, h)

    def test_getlist(self):
        self.assertEqual(self.d.getlist('cookie'), ['foo', 'bar'])
        self.assertEqual(self.d.getlist('Cookie'), ['foo', 'bar'])
        self.assertEqual(self.d.getlist('b'), [])
        self.d.add('b', 'asdf')
        self.assertEqual(self.d.getlist('b'), ['asdf'])

    def test_getlist_after_copy(self):
        self.assertEqual(self.d.getlist('cookie'), HTTPHeaderDict(self.d).getlist('cookie'))

    def test_equal(self):
        b = HTTPHeaderDict(cookie='foo, bar')
        c = NonMappingHeaderContainer(cookie='foo, bar')
        self.assertEqual(self.d, b)
        self.assertEqual(self.d, c)
        self.assertNotEqual(self.d, 2)

    def test_not_equal(self):
        b = HTTPHeaderDict(cookie='foo, bar')
        c = NonMappingHeaderContainer(cookie='foo, bar')
        self.assertFalse(self.d != b)
        self.assertFalse(self.d != c)
        self.assertNotEqual(self.d, 2)

    def test_pop(self):
        key = 'Cookie'
        a = self.d[key]
        b = self.d.pop(key)
        self.assertEqual(a, b)
        self.assertFalse(key in self.d)
        self.assertRaises(KeyError, self.d.pop, key)
        dummy = object()
        self.assertTrue(dummy is self.d.pop(key, dummy))

    def test_discard(self):
        self.d.discard('cookie')
        self.assertFalse('cookie' in self.d)
        self.d.discard('cookie')

    def test_len(self):
        self.assertEqual(len(self.d), 1)
        self.d.add('cookie', 'bla')
        self.d.add('asdf', 'foo')
        # len determined by unique fieldnames
        self.assertEqual(len(self.d), 2)

    def test_repr(self):
        rep = "HTTPHeaderDict({'Cookie': 'foo, bar'})"
        self.assertEqual(repr(self.d), rep)

    def test_items(self):
        items = self.d.items()
        self.assertEqual(len(items), 2)
        self.assertEqual(items[0][0], 'Cookie')
        self.assertEqual(items[0][1], 'foo')
        self.assertEqual(items[1][0], 'Cookie')
        self.assertEqual(items[1][1], 'bar')

    def test_dict_conversion(self):
        # Also tested in connectionpool, needs to preserve case
        hdict = {'Content-Length': '0', 'Content-type': 'text/plain', 'Server': 'TornadoServer/1.2.3'}
        h = dict(HTTPHeaderDict(hdict).items())
        self.assertEqual(hdict, h)
        self.assertEqual(hdict, dict(HTTPHeaderDict(hdict)))

    def test_string_enforcement(self):
        # This currently throws AttributeError on key.lower(), should probably be something nicer
        self.assertRaises(Exception, self.d.__setitem__, 3, 5)
        self.assertRaises(Exception, self.d.add, 3, 4)
        self.assertRaises(Exception, self.d.__delitem__, 3)
        self.assertRaises(Exception, HTTPHeaderDict, {3: 3})

    def test_from_httplib_py2(self):
        if six.PY3:
            raise SkipTest("python3 has a different internal header implementation")
        msg = """
Server: nginx
Content-Type: text/html; charset=windows-1251
Connection: keep-alive
X-Some-Multiline: asdf
 asdf
 asdf
Set-Cookie: bb_lastvisit=1348253375; expires=Sat, 21-Sep-2013 18:49:35 GMT; path=/
Set-Cookie: bb_lastactivity=0; expires=Sat, 21-Sep-2013 18:49:35 GMT; path=/
www-authenticate: asdf
www-authenticate: bla

"""
        buffer = six.moves.StringIO(msg.lstrip().replace('\n', '\r\n'))
        msg = six.moves.http_client.HTTPMessage(buffer)
        d = HTTPHeaderDict.from_httplib(msg)
        self.assertEqual(d['server'], 'nginx')
        cookies = d.getlist('set-cookie')
        self.assertEqual(len(cookies), 2)
        self.assertTrue(cookies[0].startswith("bb_lastvisit"))
        self.assertTrue(cookies[1].startswith("bb_lastactivity"))
        self.assertEqual(d['x-some-multiline'].split(), ['asdf', 'asdf', 'asdf'])
        self.assertEqual(d['www-authenticate'], 'asdf, bla')
        self.assertEqual(d.getlist('www-authenticate'), ['asdf', 'bla'])
예제 #32
0
def compare_headers(request, serialized):
    headers = HTTPHeaderDict()
    for name, value in serialized.items():
        for sub in value:
            headers.add(name, sub)
        assert request.headers[name] == headers[name]
예제 #33
0
def d():
    header_dict = HTTPHeaderDict(Cookie='foo')
    header_dict.add('cookie', 'bar')
    return header_dict
예제 #34
0
 def test_add_well_known_multiheader(self, d: HTTPHeaderDict) -> None:
     d.add("COOKIE", "asdf")
     assert d.getlist("cookie") == ["foo", "bar", "asdf"]
     assert d["cookie"] == "foo, bar, asdf"