예제 #1
0
파일: test_worker.py 프로젝트: westi/Rocket
    def testReadHeaders(self):
        headersBuf = BytesIO(
            b('\r\n').join(SAMPLE_HEADERS.splitlines()[1:]) + b('\r\n\r\n'))
        headers = self.worker.read_headers(headersBuf)

        for header_name in HEADER_DICT.keys():
            self.assertEqual(headers[header_name], HEADER_DICT[header_name])
예제 #2
0
    def testEnvironment(self):
        """The environ parameter is a dictionary object, containing CGI-style
        environment variables. This object must be a builtin Python dictionary
        (not a subclass, UserDict or other dictionary emulation), and the
        application is allowed to modify the dictionary in any way it desires.
        The dictionary must also include certain WSGI-required variables
        (described in a later section), and may also include server-specific
        extension variables, named according to a convention that will be
        described below."""
        REQUIRED_VARS = [
            ('REQUEST_METHOD', True,
             'GET|POST|PUT|DELETE|HEAD|TRACE|OPTIONS|CONNECT'),
            ('SCRIPT_NAME', True, r'([A-Za-z][A-Za-z0-9\.\-]*)?'),
            ('PATH_INFO', True, r'([A-Za-z][A-Za-z0-9\.\-]*)?'),
            ('QUERY_STRING', False, r''),
            ('CONTENT_TYPE', False, r'\w+/\w+'),
            ('CONTENT_LENGTH', False, r'\d+'),
            ('SERVER_NAME', True, r'\w+'),
            ('SERVER_PORT', True, r'\d+'),
            ('SERVER_PROTOCOL', True, r'HTTP/1\.[01]'),
            ('wsgi.version', True, lambda x: x[0] == 1 and x[1] == 0),
            ('wsgi.url_scheme', True, r'https?'),
            ('wsgi.input', True, lambda x: hasattr(x, 'read')),
            ('wsgi.errors', True, lambda x: hasattr(x, 'read')),
            ('wsgi.multithread', True, lambda x: isinstance(x, bool)),
            ('wsgi.multiprocess', True, lambda x: isinstance(x, bool)),
            ('wsgi.run_once', True, lambda x: isinstance(x, bool)),
            ('HTTP_HOST', False, r'([A-Za-z][A-Za-z0-9\.]*)?'),
        ]
        # NOTE: We could also check other HTTP_ vars but they are browser dependent.

        self.worker.conn = conn = FakeConn()

        self.worker.conn = conn

        headersBuf = StringIO(
            b('\r\n').join(SAMPLE_HEADERS.splitlines()) + b('\r\n\r\n'))
        env = self.worker.build_environ(headersBuf, conn)

        for name, reqd, validator in REQUIRED_VARS:
            if reqd:
                self.assertTrue(name in env,
                                msg="Missing Environment variable: " + name)
            if name in env:
                valid = validator
                if isinstance(valid, str):
                    valid = re.compile(valid)
                if isinstance(valid, (types.FunctionType, types.MethodType)):
                    self.assertTrue(valid(env[name]),
                                    msg="%s=\"%s\" does not validate." %
                                    (name, env[name]))
                else:
                    self.assertTrue(valid.match(env[name]),
                                    msg="%s=\"%s\" does not validate." %
                                    (name, env[name]))
예제 #3
0
def wsgiapp(environ, start_response):
    base_page = '''<html><head><title>Futures Demonstration</title></head><body>%s<br /><a href="/">Home</a></body></html>'''
    home_content = '''<h1>Futures Demonstration</h1><h2>Current Futures</h2>%s

<h2>Start a new future</h2>
<form action="/start" method="GET">
    <input name="name" type="text" placeholder="Future name"/>
    <input name="duration" type="text" placeholder="Duration (seconds)"/>
    <input type="submit" />
</form>'''

    def format_future_link(name, future):
        tpl = '''<a href="/result?name=%s">%s - %s</a>'''
        return tpl % (name, name, future._state)

    path_list = [x for x in environ['PATH_INFO'].split('/') if x]
    vars = parse_qs(environ['QUERY_STRING'])

    if 'wsgiorg.executor' not in environ:
        start_response('200 OK', [('Content-Type', 'text/html')])
        return [b("futures not supported")]
    else:
        executor = environ['wsgiorg.executor']
        futures = environ['wsgiorg.futures']

    data = base_page

    if len(path_list) == 0:
        data %= home_content % "<br/>".join([format_future_link(n, f) for n,f in futures.items()])
    elif len(path_list) == 1:
        if path_list[0] == "start" and 'name' in vars:
            try:
                f = executor.submit(wait, int(vars.get("duration", ["10"])[0]))
                if 'name' in vars:
                    f.remember(vars['name'][0])
                    data %= "\n\nJob remembered as: " + vars['name'][0]
                else:
                    data %= "\n\nJob Submitted"
            except NameError:
                data %= "\n\nJob already exists with name: " + vars['name'][0]
        elif path_list[0] == "result" and 'name' in vars:
            name = vars['name'][0]
            if name not in futures:
                data %= "No future named %s available." % name
            else:
                data %= "%s = %s" % (name, futures[name].result())
                futures[name].forget()

        else:
            data %= "\n\nUnknown action"



    start_response('200 OK', [('Content-Type', 'text/html')])
    return [b(data)]
예제 #4
0
    def testFileLikeSocketRead(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        SENT_DATA = b("this is a test")
        self.sock.send(SENT_DATA)

        f = c.makefile()
        data = b(f.read(len(SENT_DATA)))

        self.assertEqual(data, SENT_DATA)

        f.close()
예제 #5
0
    def testEnvironment(self):
        """The environ parameter is a dictionary object, containing CGI-style
        environment variables. This object must be a builtin Python dictionary
        (not a subclass, UserDict or other dictionary emulation), and the
        application is allowed to modify the dictionary in any way it desires.
        The dictionary must also include certain WSGI-required variables
        (described in a later section), and may also include server-specific
        extension variables, named according to a convention that will be
        described below."""
        REQUIRED_VARS = [
            ('REQUEST_METHOD', True, 'GET|POST|PUT|DELETE|HEAD|TRACE|OPTIONS|CONNECT'),
            ('SCRIPT_NAME', True, r'([A-Za-z][A-Za-z0-9\.\-]*)?'),
            ('PATH_INFO', True, r'([A-Za-z][A-Za-z0-9\.\-]*)?'),
            ('QUERY_STRING', False, r''),
            ('CONTENT_TYPE', False, r'\w+/\w+'),
            ('CONTENT_LENGTH', False, r'\d+'),
            ('SERVER_NAME', True, r'\w+'),
            ('SERVER_PORT', True, r'\d+'),
            ('SERVER_PROTOCOL', True, r'HTTP/1\.[01]'),
            ('wsgi.version', True, lambda x: x[0] == 1 and x[1] == 0),
            ('wsgi.url_scheme', True, r'https?'),
            ('wsgi.input', True, lambda x: hasattr(x, 'read')),
            ('wsgi.errors', True, lambda x: hasattr(x, 'read')),
            ('wsgi.multithread', True, lambda x: isinstance(x, bool)),
            ('wsgi.multiprocess', True, lambda x: isinstance(x, bool)),
            ('wsgi.run_once', True, lambda x: isinstance(x, bool)),
            ('HTTP_HOST', False, r'([A-Za-z][A-Za-z0-9\.]*)?'),
        ]
        # NOTE: We could also check other HTTP_ vars but they are browser dependent.

        self.worker.conn = conn = FakeConn()

        self.worker.conn = conn

        headersBuf = StringIO(b('\r\n').join(SAMPLE_HEADERS.splitlines()) + b('\r\n\r\n'))
        env = self.worker.build_environ(headersBuf, conn)

        for name, reqd, validator in REQUIRED_VARS:
            if reqd:
                self.assertTrue(name in env,
                             msg="Missing Environment variable: " + name)
            if name in env:
                valid = validator
                if isinstance(valid, str):
                    valid = re.compile(valid)
                if isinstance(valid, (types.FunctionType, types.MethodType)):
                    self.assertTrue(valid(env[name]),
                                 msg="%s=\"%s\" does not validate." % (name, env[name]))
                else:
                    self.assertTrue(valid.match(env[name]),
                                 msg="%s=\"%s\" does not validate." % (name, env[name]))
예제 #6
0
    def testRead(self):
        io = StringIO(SAMPLE_CHUNKED_REQUEST)
        answer = StringIO(SAMPLE_CHUNKED_ANSWER)
        chunky = worker.ChunkedReader(io)

        res = answer.read(1)
        chk = chunky.read(1)
        while res and chk:
            self.assertEqual(res, chk)
            res = answer.read(1)
            chk = chunky.read(1)

        self.assertEqual(res, b(""))
        self.assertEqual(chk, b(""))
예제 #7
0
    def testRead(self):
        io = StringIO(SAMPLE_CHUNKED_REQUEST)
        answer = StringIO(SAMPLE_CHUNKED_ANSWER)
        chunky = worker.ChunkedReader(io)

        res = answer.read(1)
        chk = chunky.read(1)
        while res and chk:
            self.assertEqual(res, chk)
            res = answer.read(1)
            chk = chunky.read(1)

        self.assertEqual(res, b(""))
        self.assertEqual(chk, b(""))
예제 #8
0
    def testReadRequestLine(self):
        self.worker.conn = FakeConn()
        for reqline, resdict in REQUEST_DICT.items():
            result = self.worker.read_request_line(BytesIO(reqline + b('\r\n')))

            for key in result:
                self.assertEqual(result[key], resdict[key])
예제 #9
0
    def testOutputHandling(self):
        """The server or gateway should treat the yielded strings as binary
        byte sequences: in particular, it should ensure that line endings are
        not altered. The application is responsible for ensuring that the
        string(s) to be written are in a format suitable for the client. (The
        server or gateway may apply HTTP transfer encodings, or perform other
        transformations for the purpose of implementing HTTP features such as
        byte-range transmission. See Other HTTP Features, below, for more
        details.)"""
        self.worker.conn = conn = FakeConn()
        sock_file = conn.makefile()

        self.worker.environ = environ = self.worker.build_environ(
            sock_file, conn)
        self.worker.error = (None, None)
        self.worker.headers_sent = True
        self.worker.chunked = False

        output = self.worker.app(environ, self.worker.start_response)

        for data in output:
            if data:
                self.worker.write(data, len(data))

        self.assertEqual(b('').join(output), conn.sendData)
예제 #10
0
    def testFileLikeSocketReadline(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        SENT_DATA = b("""this is a test\nthis is another line\n""")
        self.sock.send(SENT_DATA)

        time.sleep(0.25)

        f = c.makefile()

        try:
            for l in SENT_DATA.splitlines():
                data = b(f.readline())
                self.assertEqual(data, l+b("\n"))
        finally:
            f.close()
            c.close()
예제 #11
0
파일: test_worker.py 프로젝트: westi/Rocket
    def testReadRequestLine(self):
        self.worker.conn = FakeConn()
        for reqline, resdict in REQUEST_DICT.items():
            result = self.worker.read_request_line(BytesIO(reqline +
                                                           b('\r\n')))

            for key in result:
                self.assertEqual(result[key], resdict[key])
예제 #12
0
    def testFileLikeSocketReadlines(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        SENT_DATA = b("""this is a test\nthis is another line\n""")
        self.sock.send(SENT_DATA)
        self.sock.close()

        time.sleep(0.25)

        f = c.makefile()

        sent_lines = [x + b('\n') for x in SENT_DATA.splitlines()]
        data_lines = [b(x) for x in f.readlines()]

        self.assertEqual(sent_lines, data_lines)

        f.close()
        c.close()
예제 #13
0
    def testSocketRecv(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        SENT_DATA = b("this is a test")
        self.sock.send(SENT_DATA)

        data = c.recv(len(SENT_DATA))

        self.assertEqual(data, SENT_DATA)
예제 #14
0
    def testSocketSend(self):
        c = connection.Connection(*(self.server.active_queue.get(timeout=10)))

        RECVD_DATA = b("this is a test")
        c.send(RECVD_DATA)

        data = self.sock.recv(len(RECVD_DATA))

        self.assertEqual(data, RECVD_DATA)
예제 #15
0
 def _waitForEqual(self, a, b):
     attempts = 20
     while attempts > 0:
         if isinstance(a, (types.FunctionType, types.MethodType)):
             _a = a()
         else:
             _a = a
         if isinstance(b, (types.FunctionType, types.MethodType)):
             _b = b()
         else:
             _b = b
         if _a == _b:
             return True
         time.sleep(0.25)
         attempts -= 1
     return False
예제 #16
0
 def _waitForEqual(self, a, b):
     attempts = 20
     while attempts > 0:
         if isinstance(a, (types.FunctionType, types.MethodType)):
             _a = a()
         else:
             _a = a
         if isinstance(b, (types.FunctionType, types.MethodType)):
             _b = b()
         else:
             _b = b
         if _a == _b:
             return True
         time.sleep(0.25)
         attempts -= 1
     return False
예제 #17
0
    def testRun_HTTPConnection(self):
        conn = FakeConn()

        self.active_queue.put(conn)
        self.active_queue.put(None)

        self.worker.closeConnection = False
        self.worker.request_line = ''

        # NOTE: This test may infinite loop instead of fail.
        self.assertEqual(None, self.worker.run())

        # Test that it closed the connection
        self.assertTrue(self.worker.closeConnection)

        self.assertEqual(conn.sendData, b('HTTP/1.1 500 Server Error\nContent-Length: 12\nContent-Type: text/plain\n\nServer Error\n'))
예제 #18
0
    def testRun_HTTPConnectionOnHTTPSSocket(self):
        conn = FakeConn()
        conn.ssl = True
        conn.secure = False

        self.active_queue.put(conn)
        self.active_queue.put(None)

        self.worker.closeConnection = False

        # NOTE: This test may infinite loop instead of fail.
        self.assertEqual(None, self.worker.run())

        # Test that it closed the connection
        self.assertTrue(self.worker.closeConnection)

        # Test that it sent 400 bad request
        self.assertEqual(conn.sendData, b('HTTP/1.1 400 Bad Request\nContent-Length: 11\nContent-Type: text/plain\n\nBad Request\n'))
예제 #19
0
파일: test_worker.py 프로젝트: westi/Rocket
    def testRun_HTTPConnection(self):
        conn = FakeConn()

        self.active_queue.put(conn)
        self.active_queue.put(None)

        self.worker.closeConnection = False
        self.worker.request_line = ''

        # NOTE: This test may infinite loop instead of fail.
        self.assertEqual(None, self.worker.run())

        # Test that it closed the connection
        self.assertTrue(self.worker.closeConnection)

        self.assertEqual(
            conn.sendData,
            b('HTTP/1.1 500 Server Error\nContent-Length: 12\nContent-Type: text/plain\n\nServer Error\n'
              ))
예제 #20
0
    def testMonitor(self):
        self.testNotActive() # create self.monitor

        # Start the listener
        self.listener = listener.Listener(self.interface,
                                          5,
                                          self.active_queue)
        self.listener.start()

        # Create a socket connecting to listener's port
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(15)
        sock.connect(self.interface)

        # Verify that listener put it in the active queue
        self._waitForEqual(self.active_queue.qsize, 1)
        self.assertEqual(self.active_queue.qsize(), 1)

        self.monitor.start()

        # Put it in the monitor queue
        conn = self.active_queue.get()
        conn = connection.Connection(*conn)
        self.monitor_queue.put(conn)
        self._waitForEqual(self.monitor_queue.qsize, 1)
        self.assertEqual(self.monitor_queue.qsize(), 1)

        # Wait for the monitor queue to see it
        self._waitForEqual(self.monitor_queue.qsize, 0)
        self.assertEqual(self.monitor_queue.qsize(), 0)

        # Send something to the socket to see if it gets put back on the active
        # queue.
        sock.send(b("test data"))
        sock.close()

        # Give monitor a chance to see it
        self._waitForEqual(self.active_queue.qsize, 1)

        # Finally check to make sure that it's on the active queue
        self.assertEqual(self.active_queue.qsize(), 1)
        conn2 = self.active_queue.get()
        self.assertTrue(conn is conn2)
예제 #21
0
    def testMonitor(self):
        self.testNotActive()  # create self.monitor

        # Start the listener
        self.listener = listener.Listener(self.interface, 5, self.active_queue)
        self.listener.start()

        # Create a socket connecting to listener's port
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(15)
        sock.connect(self.interface)

        # Verify that listener put it in the active queue
        self._waitForEqual(self.active_queue.qsize, 1)
        self.assertEqual(self.active_queue.qsize(), 1)

        self.monitor.start()

        # Put it in the monitor queue
        conn = self.active_queue.get()
        conn = connection.Connection(*conn)
        self.monitor_queue.put(conn)
        self._waitForEqual(self.monitor_queue.qsize, 1)
        self.assertEqual(self.monitor_queue.qsize(), 1)

        # Wait for the monitor queue to see it
        self._waitForEqual(self.monitor_queue.qsize, 0)
        self.assertEqual(self.monitor_queue.qsize(), 0)

        # Send something to the socket to see if it gets put back on the active
        # queue.
        sock.send(b("test data"))
        sock.close()

        # Give monitor a chance to see it
        self._waitForEqual(self.active_queue.qsize, 1)

        # Finally check to make sure that it's on the active queue
        self.assertEqual(self.active_queue.qsize(), 1)
        conn2 = self.active_queue.get()
        self.assertTrue(conn is conn2)
예제 #22
0
파일: test_worker.py 프로젝트: westi/Rocket
    def testRun_HTTPConnectionOnHTTPSSocket(self):
        conn = FakeConn()
        conn.ssl = True
        conn.secure = False

        self.active_queue.put(conn)
        self.active_queue.put(None)

        self.worker.closeConnection = False

        # NOTE: This test may infinite loop instead of fail.
        self.assertEqual(None, self.worker.run())

        # Test that it closed the connection
        self.assertTrue(self.worker.closeConnection)

        # Test that it sent 400 bad request
        self.assertEqual(
            conn.sendData,
            b('HTTP/1.1 400 Bad Request\nContent-Length: 11\nContent-Type: text/plain\n\nBad Request\n'
              ))
예제 #23
0
    def testOutputHandling(self):
        """The server or gateway should treat the yielded strings as binary
        byte sequences: in particular, it should ensure that line endings are
        not altered. The application is responsible for ensuring that the
        string(s) to be written are in a format suitable for the client. (The
        server or gateway may apply HTTP transfer encodings, or perform other
        transformations for the purpose of implementing HTTP features such as
        byte-range transmission. See Other HTTP Features, below, for more
        details.)"""
        self.worker.conn = conn = FakeConn()
        sock_file = conn.makefile()

        self.worker.environ = environ = self.worker.build_environ(sock_file, conn)
        self.worker.error = (None, None)
        self.worker.headers_sent = True
        self.worker.chunked = False

        output = self.worker.app(environ, self.worker.start_response)

        for data in output:
            if data:
                self.worker.write(data, len(data))

        self.assertEqual(b('').join(output), conn.sendData)
예제 #24
0
파일: test_worker.py 프로젝트: westi/Rocket
        from cStringIO import StringIO as BytesIO
    except ImportError:
        from StringIO import StringIO as BytesIO

# Import Custom Modules
from rocket import worker, IS_JYTHON, b

# Constants
SERVER_PORT = 45451 if IS_JYTHON else -1
SAMPLE_HEADERS = b('''\
GET /dumprequest HTTP/1.1
Host: djce.org.uk
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.12) Gecko/20101027 Ubuntu/10.04 (lucid) Firefox/3.6.12
Accept: text/html,application/xhtml+xml
 application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://www.google.com/custom?hl=en&client=pub-9300639326172081&cof=FORID%3A13%3BAH%3Aleft%3BCX%3AUbuntu%252010%252E04%3BL%3Ahttp%3A%2F%2Fwww.google.com%2Fintl%2Fen%2Fimages%2Flogos%2Fcustom_search_logo_sm.gif%3BLH%3A30%3BLP%3A1%3BLC%3A%230000ff%3BVLC%3A%23663399%3BDIV%3A%23336699%3B&adkw=AELymgUf3P4j5tGCivvOIh-_XVcEYuoUTM3M5ETKipHcRApl8ocXgO_F5W_FOWHqlk4s4luYT_xQ10u8aDk2dEwgEYDYgHezJRTj7dx64CHnuTwPVLVChMA&channel=6911402799&q=http+request+header+sample&btnG=Search&cx=partner-pub-9300639326172081%3Ad9bbzbtli15'''
                   )
HEADER_DICT = {
    'HOST':
    'djce.org.uk',
    'USER_AGENT':
    'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.12) Gecko/20101027 Ubuntu/10.04 (lucid) Firefox/3.6.12',
    'ACCEPT':
    'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'ACCEPT_LANGUAGE':
    'en-us,en;q=0.5',
예제 #25
0
 def makefile(mode="rb", buf_size=1024):
     return StringIO(b('\r\n').join(SAMPLE_HEADERS.splitlines()) + b('\r\n\r\n'))
예제 #26
0
 def sendall(self, data):
     self.sendData = data
     if data.lower().strip().endswith(b("error")):
         raise socket.error
예제 #27
0
 def testBytes(self):
     self.assertEquals(rocket.b('abc'), 'abc')
     self.assertEquals(type(rocket.b('abc')), type('abc'))
예제 #28
0
 def sendall(self, data):
     self.sendData = data
     if data.lower().strip().endswith(b("error")):
         raise socket.error
예제 #29
0
    try:
        from cStringIO import StringIO
    except ImportError:
        from StringIO import StringIO

# Import Custom Modules
from rocket import worker, b

# Constants
SAMPLE_CHUNKED_REQUEST = b('''\
25\r
This is the data in the first chunk\r
\r
1C\r
and this is the second one\r
\r
3\r
con\r
8\r
sequence\r
0\r
\r
''')
SAMPLE_CHUNKED_ANSWER = b('''\
This is the data in the first chunk\r
and this is the second one\r
consequence''')


class FakeConn:
    def sendall(self, data):
        if data.lower().strip().endswith("error"):
예제 #30
0
    try:
        from cStringIO import StringIO as BytesIO
    except ImportError:
        from StringIO import StringIO as BytesIO

# Import Custom Modules
from rocket import worker, IS_JYTHON, b

# Constants
SERVER_PORT = 45451 if IS_JYTHON else -1
SAMPLE_HEADERS = b('''\
GET /dumprequest HTTP/1.1
Host: djce.org.uk
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.12) Gecko/20101027 Ubuntu/10.04 (lucid) Firefox/3.6.12
Accept: text/html,application/xhtml+xml
 application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://www.google.com/custom?hl=en&client=pub-9300639326172081&cof=FORID%3A13%3BAH%3Aleft%3BCX%3AUbuntu%252010%252E04%3BL%3Ahttp%3A%2F%2Fwww.google.com%2Fintl%2Fen%2Fimages%2Flogos%2Fcustom_search_logo_sm.gif%3BLH%3A30%3BLP%3A1%3BLC%3A%230000ff%3BVLC%3A%23663399%3BDIV%3A%23336699%3B&adkw=AELymgUf3P4j5tGCivvOIh-_XVcEYuoUTM3M5ETKipHcRApl8ocXgO_F5W_FOWHqlk4s4luYT_xQ10u8aDk2dEwgEYDYgHezJRTj7dx64CHnuTwPVLVChMA&channel=6911402799&q=http+request+header+sample&btnG=Search&cx=partner-pub-9300639326172081%3Ad9bbzbtli15''')
HEADER_DICT = {
    'HOST': 'djce.org.uk',
    'USER_AGENT': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.12) Gecko/20101027 Ubuntu/10.04 (lucid) Firefox/3.6.12',
    'ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'ACCEPT_LANGUAGE': 'en-us,en;q=0.5',
    'ACCEPT_ENCODING': 'gzip,deflate',
    'ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
    'KEEP_ALIVE': '115',
    'CONNECTION': 'keep-alive',
    'REFERER': 'http://www.google.com/custom?hl=en&client=pub-9300639326172081&cof=FORID%3A13%3BAH%3Aleft%3BCX%3AUbuntu%252010%252E04%3BL%3Ahttp%3A%2F%2Fwww.google.com%2Fintl%2Fen%2Fimages%2Flogos%2Fcustom_search_logo_sm.gif%3BLH%3A30%3BLP%3A1%3BLC%3A%230000ff%3BVLC%3A%23663399%3BDIV%3A%23336699%3B&adkw=AELymgUf3P4j5tGCivvOIh-_XVcEYuoUTM3M5ETKipHcRApl8ocXgO_F5W_FOWHqlk4s4luYT_xQ10u8aDk2dEwgEYDYgHezJRTj7dx64CHnuTwPVLVChMA&channel=6911402799&q=http+request+header+sample&btnG=Search&cx=partner-pub-9300639326172081%3Ad9bbzbtli15'}
예제 #31
0
 def sendall(self, data):
     self.sendData = data
     if data.lower().strip().endswith(b("error")):
         raise socket.error
     else:
         assert data in SENDALL_VALUES
예제 #32
0
    def testReadHeaders(self):
        headersBuf = BytesIO(b('\r\n').join(SAMPLE_HEADERS.splitlines()[1:]) + b('\r\n\r\n'))
        headers = self.worker.read_headers(headersBuf)

        for header_name in HEADER_DICT.keys():
            self.assertEqual(headers[header_name], HEADER_DICT[header_name])
예제 #33
0
 def testReadRequestLineErrors(self):
     self.worker.conn = FakeConn()
     for reqline in BAD_REQUESTS:
         self.assertRaises(worker.BadRequest,
                           self.worker.read_request_line,
                           BytesIO(reqline + b('\r\n')))
예제 #34
0
파일: test_worker.py 프로젝트: westi/Rocket
 def sendall(self, data):
     self.sendData = data
     if data.lower().strip().endswith(b("error")):
         raise socket.error
     else:
         assert data in SENDALL_VALUES
예제 #35
0
    try:
        from cStringIO import StringIO
    except ImportError:
        from StringIO import StringIO

# Import Custom Modules
from rocket import worker, b

# Constants
SAMPLE_CHUNKED_REQUEST = b('''\
25\r
This is the data in the first chunk\r
\r
1C\r
and this is the second one\r
\r
3\r
con\r
8\r
sequence\r
0\r
\r
''')
SAMPLE_CHUNKED_ANSWER = b('''\
This is the data in the first chunk\r
and this is the second one\r
consequence''')

class FakeConn:
    def sendall(self, data):
        if data.lower().strip().endswith("error"):
            raise socket.error
예제 #36
0
 def makefile(mode="rb", buf_size=1024):
     return StringIO(
         b('\r\n').join(SAMPLE_HEADERS.splitlines()) + b('\r\n\r\n'))
예제 #37
0
    except ImportError:
        from StringIO import StringIO

from wsgiref.simple_server import demo_app

# Import Custom Modules
from rocket import b
from rocket.methods import wsgi

# Constants
SAMPLE_HEADERS = b('''\
GET /dumprequest HTTP/1.1
Host: djce.org.uk
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.12) Gecko/20101027 Ubuntu/10.04 (lucid) Firefox/3.6.12
Accept: text/html,application/xhtml+xml
 application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://www.google.com/custom?hl=en&client=pub-9300639326172081&cof=FORID%3A13%3BAH%3Aleft%3BCX%3AUbuntu%252010%252E04%3BL%3Ahttp%3A%2F%2Fwww.google.com%2Fintl%2Fen%2Fimages%2Flogos%2Fcustom_search_logo_sm.gif%3BLH%3A30%3BLP%3A1%3BLC%3A%230000ff%3BVLC%3A%23663399%3BDIV%3A%23336699%3B&adkw=AELymgUf3P4j5tGCivvOIh-_XVcEYuoUTM3M5ETKipHcRApl8ocXgO_F5W_FOWHqlk4s4luYT_xQ10u8aDk2dEwgEYDYgHezJRTj7dx64CHnuTwPVLVChMA&channel=6911402799&q=http+request+header+sample&btnG=Search&cx=partner-pub-9300639326172081%3Ad9bbzbtli15''')
HEADER_DICT = {
    'host': 'djce.org.uk',
    'user_agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.12) Gecko/20101027 Ubuntu/10.04 (lucid) Firefox/3.6.12',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'accept_language': 'en-us,en;q=0.5',
    'accept_encoding': 'gzip,deflate',
    'accept_charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
    'keep_alive': '115',
    'connection': 'keep-alive',
    'referer': 'http://www.google.com/custom?hl=en&client=pub-9300639326172081&cof=FORID%3A13%3BAH%3Aleft%3BCX%3AUbuntu%252010%252E04%3BL%3Ahttp%3A%2F%2Fwww.google.com%2Fintl%2Fen%2Fimages%2Flogos%2Fcustom_search_logo_sm.gif%3BLH%3A30%3BLP%3A1%3BLC%3A%230000ff%3BVLC%3A%23663399%3BDIV%3A%23336699%3B&adkw=AELymgUf3P4j5tGCivvOIh-_XVcEYuoUTM3M5ETKipHcRApl8ocXgO_F5W_FOWHqlk4s4luYT_xQ10u8aDk2dEwgEYDYgHezJRTj7dx64CHnuTwPVLVChMA&channel=6911402799&q=http+request+header+sample&btnG=Search&cx=partner-pub-9300639326172081%3Ad9bbzbtli15'
예제 #38
0
파일: test_worker.py 프로젝트: westi/Rocket
 def testReadRequestLineErrors(self):
     self.worker.conn = FakeConn()
     for reqline in BAD_REQUESTS:
         self.assertRaises(worker.BadRequest, self.worker.read_request_line,
                           BytesIO(reqline + b('\r\n')))
예제 #39
0
 def testBytes(self):
     if PY3K:
         self.skipTest("Not a valid test in Python 3")
     self.assertEqual(rocket.b('abc'), 'abc')
     self.assertEqual(type(rocket.b('abc')), type('abc'))
예제 #40
0
        from StringIO import StringIO

from wsgiref.simple_server import demo_app

# Import Custom Modules
from rocket import b
from rocket.methods import wsgi

# Constants
SAMPLE_HEADERS = b('''\
GET /dumprequest HTTP/1.1
Host: djce.org.uk
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.12) Gecko/20101027 Ubuntu/10.04 (lucid) Firefox/3.6.12
Accept: text/html,application/xhtml+xml
 application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Referer: http://www.google.com/custom?hl=en&client=pub-9300639326172081&cof=FORID%3A13%3BAH%3Aleft%3BCX%3AUbuntu%252010%252E04%3BL%3Ahttp%3A%2F%2Fwww.google.com%2Fintl%2Fen%2Fimages%2Flogos%2Fcustom_search_logo_sm.gif%3BLH%3A30%3BLP%3A1%3BLC%3A%230000ff%3BVLC%3A%23663399%3BDIV%3A%23336699%3B&adkw=AELymgUf3P4j5tGCivvOIh-_XVcEYuoUTM3M5ETKipHcRApl8ocXgO_F5W_FOWHqlk4s4luYT_xQ10u8aDk2dEwgEYDYgHezJRTj7dx64CHnuTwPVLVChMA&channel=6911402799&q=http+request+header+sample&btnG=Search&cx=partner-pub-9300639326172081%3Ad9bbzbtli15'''
                   )
HEADER_DICT = {
    'host':
    'djce.org.uk',
    'user_agent':
    'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.12) Gecko/20101027 Ubuntu/10.04 (lucid) Firefox/3.6.12',
    'accept':
    'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'accept_language':
    'en-us,en;q=0.5',
예제 #41
0
 def testBytes(self):
     self.assertEquals(rocket.b('abc'), 'abc')
     self.assertEquals(type(rocket.b('abc')), type('abc'))