Beispiel #1
0
    def test_get_lower(self):
        i_headers = multidict.MultiDict([('test', '123')])
        o_headers = multidict.MultiDict([('TEST', '123')])

        atoms = helpers.SafeAtoms({}, i_headers, o_headers)
        self.assertEqual(atoms['{test}i'], '123')
        self.assertEqual(atoms['{test}o'], '-')
        self.assertEqual(atoms['{TEST}o'], '123')
        self.assertEqual(atoms['{UNKNOWN}o'], '-')
        self.assertEqual(atoms['{UNKNOWN}'], '-')
Beispiel #2
0
 def test_http_1_0_no_host(self):
     headers = multidict.MultiDict({})
     self.message = protocol.RawRequestMessage(
         'GET', '/', (1, 0), headers, [], True, 'deflate')
     environ = self._make_one()
     self.assertEqual(environ['SERVER_NAME'], '2.3.4.5')
     self.assertEqual(environ['SERVER_PORT'], '80')
Beispiel #3
0
 def test_http_payload_parser_length_wrong(self):
     msg = protocol.RawRequestMessage(
         'GET', '/', (1, 1),
         multidict.MultiDict([('CONTENT-LENGTH', '-1')]), None, None)
     out = aiohttp.FlowControlDataQueue(self.stream)
     buf = aiohttp.ParserBuffer()
     p = protocol.HttpPayloadParser(msg)(out, buf)
     self.assertRaises(errors.InvalidHeader, next, p)
Beispiel #4
0
 def test_http_payload_parser_no_length(self):
     msg = protocol.RawRequestMessage(
         'GET', '/', (1, 1), multidict.MultiDict(), None, None)
     out = aiohttp.FlowControlDataQueue(self.stream)
     buf = aiohttp.ParserBuffer()
     p = protocol.HttpPayloadParser(msg, readall=False)(out, buf)
     self.assertRaises(StopIteration, next, p)
     self.assertEqual(b'', b''.join(out._buffer))
     self.assertTrue(out._eof)
Beispiel #5
0
 def test_http_payload_parser_length_zero(self):
     msg = protocol.RawRequestMessage(
         'GET', '/', (1, 1),
         multidict.MultiDict([('CONTENT-LENGTH', '0')]), None, None)
     out = aiohttp.FlowControlDataQueue(self.stream)
     buf = aiohttp.ParserBuffer()
     p = protocol.HttpPayloadParser(msg)(out, buf)
     self.assertRaises(StopIteration, next, p)
     self.assertEqual(b'', b''.join(out._buffer))
Beispiel #6
0
 def test_http_payload_parser_websocket(self):
     msg = protocol.RawRequestMessage(
         'GET', '/', (1, 1),
         multidict.MultiDict([('SEC-WEBSOCKET-KEY1', '13')]), None, None)
     out = aiohttp.FlowControlDataQueue(self.stream)
     buf = aiohttp.ParserBuffer()
     p = protocol.HttpPayloadParser(msg)(out, buf)
     next(p)
     self.assertRaises(StopIteration, p.send, b'1234567890')
     self.assertEqual(b'12345678', b''.join(out._buffer))
Beispiel #7
0
 def test_http_payload_parser_eof(self):
     msg = protocol.RawRequestMessage(
         'GET', '/', (1, 1), multidict.MultiDict(), None, None)
     out = aiohttp.FlowControlDataQueue(self.stream)
     buf = aiohttp.ParserBuffer()
     p = protocol.HttpPayloadParser(msg, readall=True)(out, buf)
     next(p)
     p.send(b'data')
     p.send(b'line')
     self.assertRaises(StopIteration, p.throw, aiohttp.EofStream())
     self.assertEqual(b'dataline', b''.join(out._buffer))
Beispiel #8
0
 def test_http_request_parser_two_slashes(self):
     out = aiohttp.FlowControlDataQueue(self.stream)
     buf = aiohttp.ParserBuffer()
     p = protocol.HttpRequestParser()(out, buf)
     next(p)
     try:
         p.send(b'get //path HTTP/1.1\r\n\r\n')
     except StopIteration:
         pass
     self.assertEqual(
         ('GET', '//path', (1, 1), multidict.MultiDict(), False, None),
         out._buffer[0])
Beispiel #9
0
 def test_http_payload_parser_chunked(self):
     msg = protocol.RawRequestMessage(
         'GET', '/', (1, 1),
         multidict.MultiDict([('TRANSFER-ENCODING', 'chunked')]),
         None, None)
     out = aiohttp.FlowControlDataQueue(self.stream)
     buf = aiohttp.ParserBuffer()
     p = protocol.HttpPayloadParser(msg)(out, buf)
     next(p)
     self.assertRaises(StopIteration, p.send,
                       b'4;test\r\ndata\r\n4\r\nline\r\n0\r\ntest\r\n')
     self.assertEqual(b'dataline', b''.join(out._buffer))
Beispiel #10
0
    def test_http_payload_parser_deflate_disabled(self):
        msg = protocol.RawRequestMessage(
            'GET', '/', (1, 1),
            multidict.MultiDict([('CONTENT-LENGTH', len(self._COMPRESSED))]),
            None, 'deflate')

        out = aiohttp.FlowControlDataQueue(self.stream)
        buf = aiohttp.ParserBuffer()
        p = protocol.HttpPayloadParser(msg, compression=False)(out, buf)
        next(p)
        self.assertRaises(StopIteration, p.send, self._COMPRESSED)
        self.assertEqual(self._COMPRESSED, b''.join(out._buffer))
    def test_HTTP_200_GET_MultiDict_PARAMS(self):
        with test_utils.run_server(self.loop, router=Functional) as httpd:
            r = self.loop.run_until_complete(
                client.request('get', httpd.url('method', 'get'),
                               params=multidict.MultiDict(
                                   [('q', 'test1'), ('q', 'test2')]),
                               loop=self.loop))
            content = self.loop.run_until_complete(r.content.read())
            content = content.decode()

            self.assertIn('"query": "q=test1&q=test2"', content)
            self.assertEqual(r.status, 200)
            r.close()
    def test_POST_MultiDict(self):
        with test_utils.run_server(self.loop, router=Functional) as httpd:
            url = httpd.url('method', 'post')
            r = self.loop.run_until_complete(
                client.request('post', url, data=multidict.MultiDict(
                    [('q', 'test1'), ('q', 'test2')]),
                    loop=self.loop))
            self.assertEqual(r.status, 200)

            content = self.loop.run_until_complete(r.json())
            self.assertEqual({'q': ['test1', 'test2']}, content['form'])
            self.assertEqual(r.status, 200)
            r.close()
Beispiel #13
0
    def test_http_payload_parser_length(self):
        msg = protocol.RawRequestMessage(
            'GET', '/', (1, 1),
            multidict.MultiDict([('CONTENT-LENGTH', '2')]), None, None)
        out = aiohttp.FlowControlDataQueue(self.stream)
        buf = aiohttp.ParserBuffer()
        p = protocol.HttpPayloadParser(msg)(out, buf)
        next(p)
        try:
            p.send(b'1245')
        except StopIteration:
            pass

        self.assertEqual(b'12', b''.join(out._buffer))
        self.assertEqual(b'45', bytes(buf))
Beispiel #14
0
 def test_family_unix(self):
     if not hasattr(socket, "AF_UNIX"):
         self.skipTest("No UNIX address family. (Windows?)")
     self.transport.get_extra_info.side_effect = [
         mock.Mock(family=socket.AF_UNIX)]
     headers = multidict.MultiDict({
         'SERVER_NAME': '1.2.3.4', 'SERVER_PORT': '5678',
         'REMOTE_ADDR': '4.3.2.1', 'REMOTE_PORT': '8765'})
     self.message = protocol.RawRequestMessage(
         'GET', '/', (1, 0), headers, self.raw_headers, True, 'deflate')
     environ = self._make_one()
     self.assertEqual(environ['SERVER_NAME'], '1.2.3.4')
     self.assertEqual(environ['SERVER_PORT'], '5678')
     self.assertEqual(environ['REMOTE_ADDR'], '4.3.2.1')
     self.assertEqual(environ['REMOTE_PORT'], '8765')
Beispiel #15
0
 def __init__(self,
              path: str = None,
              *,
              search_dirs=None,
              swagger=True,
              encoding=None):
     super().__init__()
     self.app = None
     self._routes = multidict.MultiDict()
     self._encoding = encoding
     self._search_dirs = search_dirs or []
     self._swagger_data = {}
     self._swagger_yaml = {}
     self._swagger = swagger
     if path:
         self.include(path)
Beispiel #16
0
    def test_POST_FILES_IO_WITH_PARAMS(self):
        with test_utils.run_server(self.loop, router=Functional) as httpd:
            url = httpd.url('method', 'post')

            data = io.BytesIO(b'data')

            r = self.loop.run_until_complete(
                client.request('post',
                               url,
                               data=(('test', 'true'),
                                     multidict.MultiDict([('q', 't1'),
                                                          ('q', 't2')]),
                                     (data, )),
                               loop=self.loop))

            content = self.loop.run_until_complete(r.json())

            self.assertEqual(4, len(content['multipart-data']))
            self.assertEqual(
                {
                    'content-type': 'text/plain',
                    'data': 'true',
                    'name': 'test'
                }, content['multipart-data'][0])
            self.assertEqual(
                {
                    'content-type': 'text/plain',
                    'data': 'data',
                    'filename': 'unknown',
                    'name': 'unknown'
                }, content['multipart-data'][1])
            self.assertEqual(
                {
                    'content-type': 'text/plain',
                    'data': 't1',
                    'name': 'q'
                }, content['multipart-data'][2])
            self.assertEqual(
                {
                    'content-type': 'text/plain',
                    'data': 't2',
                    'name': 'q'
                }, content['multipart-data'][3])
            self.assertEqual(r.status, 200)
            r.close()
Beispiel #17
0
    def setUp(self):
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(None)

        self.wsgi = unittest.mock.Mock()
        self.reader = unittest.mock.Mock()
        self.writer = unittest.mock.Mock()
        self.writer.drain.return_value = ()
        self.transport = unittest.mock.Mock()
        self.transport.get_extra_info.return_value = '127.0.0.1'

        self.headers = multidict.MultiDict()
        self.message = protocol.RawRequestMessage(
            'GET', '/path', (1, 0), self.headers, True, 'deflate')
        self.payload = aiohttp.FlowControlDataQueue(self.reader)
        self.payload.feed_data(b'data')
        self.payload.feed_data(b'data')
        self.payload.feed_eof()
Beispiel #18
0
 def __init__(self,
              path: str,
              *,
              search_dirs=None,
              swagger=True,
              encoding=None):
     self.app = None
     self._routes = multidict.MultiDict()
     self._encoding = encoding
     search_dirs = search_dirs or ()
     self._swagger_root = utils.find_file(path, search_dirs)
     self._search_dirs = search_dirs or [
         os.path.dirname(self._swagger_root)
     ]
     if swagger:
         self._swagger_data = self.include(file_path=self._swagger_root)
         self._swagger_yaml = yaml.dump(self._swagger_data)
     self._swagger = swagger
Beispiel #19
0
    def setUp(self):
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(None)

        self.wsgi = unittest.mock.Mock()
        self.reader = unittest.mock.Mock()
        self.writer = unittest.mock.Mock()
        self.writer.drain.return_value = ()
        self.transport = unittest.mock.Mock()
        self.transport.get_extra_info.side_effect = [('1.2.3.4', 1234),
                                                     ('2.3.4.5', 80)]

        self.headers = multidict.MultiDict({"HOST": "python.org"})
        self.message = protocol.RawRequestMessage('GET', '/path', (1, 0),
                                                  self.headers, True,
                                                  'deflate')
        self.payload = aiohttp.FlowControlDataQueue(self.reader)
        self.payload.feed_data(b'data', 4)
        self.payload.feed_data(b'data', 4)
        self.payload.feed_eof()
Beispiel #20
0
    def parse_headers(self, lines):
        """Parses RFC2822 headers from a stream.

        Line continuations are supported. Returns list of header name
        and value pairs. Header name is in upper case.
        """
        close_conn = None
        encoding = None
        headers = []

        lines_idx = 1
        line = lines[1]

        while line:
            header_length = len(line)

            # Parse initial header name : value pair.
            try:
                name, value = line.split(':', 1)
            except ValueError:
                raise ValueError('Invalid header: {}'.format(line)) from None

            name = name.strip(' \t').upper()
            if HDRRE.search(name):
                raise ValueError('Invalid header name: {}'.format(name))

            # next line
            lines_idx += 1
            line = lines[lines_idx]

            # consume continuation lines
            continuation = line and line[0] in CONTINUATION

            if continuation:
                value = [value]
                while continuation:
                    header_length += len(line)
                    if header_length > self.max_field_size:
                        raise errors.LineTooLong(
                            'limit request headers fields size')
                    value.append(line)

                    # next line
                    lines_idx += 1
                    line = lines[lines_idx]
                    continuation = line[0] in CONTINUATION
                value = '\r\n'.join(value)
            else:
                if header_length > self.max_field_size:
                    raise errors.LineTooLong(
                        'limit request headers fields size')

            value = value.strip()

            # keep-alive and encoding
            if name == 'CONNECTION':
                v = value.lower()
                if v == 'close':
                    close_conn = True
                elif v == 'keep-alive':
                    close_conn = False
            elif name == 'CONTENT-ENCODING':
                enc = value.lower()
                if enc in ('gzip', 'deflate'):
                    encoding = enc

            headers.append((name, value))

        return multidict.MultiDict(headers), close_conn, encoding
def message():
    headers = multidict.MultiDict()
    return protocol.RawRequestMessage('GET', '/path', (1, 0), headers, [],
                                      True, None)
Beispiel #22
0
 def setUp(self):
     self.transport = unittest.mock.Mock()
     self.headers = multidict.MultiDict()
     self.message = protocol.RawRequestMessage('GET', '/path', (1, 0),
                                               self.headers, True, None)
Beispiel #23
0
 def test_get_non_existing(self):
     atoms = helpers.SafeAtoms({}, multidict.MultiDict(),
                               multidict.MultiDict())
     self.assertEqual(atoms['unknown'], '-')