Example #1
0
def return_concurrent_request():
    ADDR = ('127.0.0.1', 8000)
    socket = g.socket(
        g.AF_INET, g.SOCK_STREAM, g.IPPROTO_IP
    )

    socket.bind(ADDR)
    socket.listen(5)
    while True:
        try:
            conn, addr = socket.accept()
            request = ""
            while True:
                msg = conn.recv(1024)
                request += msg
                if len(msg) < 1024:
                    break
            try:
                response = server.response_ok(server.parse_request(request))
            except ValueError as detail:
                response = server.response_error(b"400", str(detail))
            except LookupError as detail:
                response = server.response_error(b"404", str(detail))
            except AttributeError as detail:
                response = server.response_error(b"405", str(detail))
            except NotImplementedError as detail:
                response = server.response_error(b"400", str(detail))
            except UserWarning as detail:
                response = server.response_error(b"403", str(detail))
            conn.sendall(response)
            conn.close()
        except KeyboardInterrupt:
            break
def set_server(conn, adr):
    while True:
        try:
            msg = ""
            while True:
                msg_chunk = conn.recv(64)
                msg += msg_chunk
                if len(msg_chunk) < 64:
                    try:
                        resp_uri = server.parse_request(msg)
                    except ValueError:
                        response = server.response_error(400, b"Bad Request")
                    except NotImplementedError:
                        response = server.response_error(505, b"Version Not Supported")
                    except IndexError:
                        response = server.response_error(405, b"Method Not Allowed")
                    except LookupError:
                        response = server.response_error(404, b"Not Found")
                    except Exception:
                        response = server.response_error(500, b"Internal Server Error")
                    else:
                        response = server.response_ok(resp_uri)

                    conn.sendall(response)
                    conn.close()

        except KeyboardInterrupt:
            break
Example #3
0
def test_response_ok(server_setup):
    test_body = b'body contents'
    response = server.response_ok(test_body, 'text/html', len(test_body))
    assert response == _CRLF.join([
        b'HTTP/1.1 200 OK',
        b'Content-Type: text/html',
        b'Content-Length: 13',
        test_body,
        b''])
def test_response_ok():
    """Test response_ok function."""
    from server import response_ok
    request_tuple = ("text/plain", "This is a very simple text file. Just to show that we can serve it up. It is three lines long.".encode('ascii'))
    SUCCESS_RESPONSE = ("""HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 94\r\n\r\nThis is a very simple text file. Just to show that we can serve it up. It is three lines long.""")
    response = response_ok(request_tuple)
    response = response.decode('utf-8')
    split_response = response.split('\r\n')
    split_success = SUCCESS_RESPONSE.split('\r\n')
    assert split_response[1] == split_success[1]
def test_response_break():
    """Test responses for blank break line between header and body."""
    from server import response_ok
    from server import response_error
    good_resp_msg = response_ok()
    bad_resp_msg = response_error("500", "some text")

    good_split = good_resp_msg.split("\r\n\r\n")
    bad_split = bad_resp_msg.split("\r\n\r\n")

    assert len(good_split) == 2
    assert len(bad_split) == 2
Example #6
0
def test_response_ok():
    body = 'this is a response'
    ctype = 'text/plain'
    response = response_ok(body, ctype)
    headers, rbody = process_response(response)
    assert rbody == body
    assert headers[0] == 'HTTP/1.1 200 OK'
    typefound = False
    for header in headers:
        if 'Content-Type: text/plain' in header:
            typefound = True
            break
    assert typefound
def test_response_headers():
    """Test responses for proper headers."""
    from server import response_ok
    from server import response_error
    good_resp_msg = response_ok()
    bad_resp_msg = response_error("500", "some text")

    good_split = good_resp_msg.split("\r\n")
    bad_split = bad_resp_msg.split("\r\n")

    assert good_split[1][:7:] == "Content"
    assert good_split[1][12] == ":"
    assert bad_split[1] == ""
Example #8
0
def test_response_ok():
    from server import response_ok
    response = response_ok()
    lines = response.split('\n')
    init_line = lines[0].split(' ')
    second_line = lines[1].split(' ')
    assert len(lines) >= 1
    assert '200' in init_line[1]
    assert init_line[0][:4] == 'HTTP'
    assert 'OK' in init_line[2]
    assert 'Content-Type:' in second_line[0]
    assert 'text/plain' in second_line[1]
    assert '\r\n' in response
def test_response_status():
    """Test responses for presence of status code and protocol."""
    from server import response_ok
    from server import response_error
    good_resp_msg = response_ok()
    bad_resp_msg = response_error("500", "some text")

    good_split = good_resp_msg.split(" ")
    bad_split = bad_resp_msg.split(" ")

    assert good_split[1][:1:] == "2"
    assert bad_split[1][:1:] == "5"
    assert good_split[0] == "HTTP/1.1"
    assert bad_split[0] == "HTTP/1.1"
Example #10
0
def test_ok():
    """Test to get correct server response."""
    from server import response_ok
    msg = response_ok()
    msg = msg.split()
    HTTP = msg[0]
    status_code = msg[1]
    content_type = msg[4]
    charset = msg[5]
    body = (str(msg[15] + msg[16]))

    assert HTTP == 'HTTP/1.1'
    assert status_code == '200'
    assert content_type == 'text/plain;'
    assert charset == 'charset=utf-8'
    assert body == "HelloWorld"
Example #11
0
def server_handler(connection, address):
    """Handles the gevent StreamServer for individual clients."""
    try:
        result, mime = parse_request(server_read(connection))
        print("log:", result)
        to_send = response_ok(result, mime)
        server_response(to_send, connection)
    except Exception as error:
        try:
            error = error.args[0]
            code = int(error.split(':')[0])
            error = error.split(':')[1].strip()
        except:
            code = 500
            error = "Server Error"
        server_response(response_error(code, error), connection)
    finally:
        connection.close()
Example #12
0
def server(conn, address):
    """Return message to client."""
    try:
        buffer_length = 8
        reply_complete = False
        full_string = u""
        while not reply_complete:
            part = conn.recv(buffer_length)
            full_string = full_string + part.decode('utf-8')
            if len(part) < buffer_length:
                reply_complete = True
        print(full_string)
        try:
            uri = parse_request(full_string)
            body_tuple = resolve_uri(uri)
            if body_tuple:
                conn.send(response_ok(body_tuple))
            else:
                conn.sendall(response_error(u'404 Page Not Found'))
            conn.close()
        except NameError('Method not GET'):
            conn.sendall(response_error(u'405 Method Not Allowed'))
            conn.close()
        except TypeError('HTTP protol incorrect'):
            conn.sendall(response_error(u'505 HTTP Version Not Supported'))
            conn.close()
        except SyntaxError('URI incorrect'):
            conn.sendall(response_error(u'404 Page Not Found'))
            conn.close()
        except IOError('File not found'):
            conn.sendall(response_error(u'404 Page Not Found'))
            conn.close()
    except SystemError('Request not fully received'):
        conn.sendall(response_error())
        conn.close()
    except KeyboardInterrupt:
        conn.close()
    finally:
        conn.close()
def test_response_ok():
    response = server.response_ok(b"123456789", "text/plain")
    assert "text/plain" in response
    assert '9' in response
Example #14
0
def test_response_ok():
    """Test that response_ok returns '200 OK' if connection is good."""
    from server import response_ok
    assert response_ok().split(b'\r\n')[0] == b'HTTP/1.1 %s' % OK_200
Example #15
0
def test_response_ok():
    response = server.response_ok().split(b'\r\n')
    assert b"HTTP/1.1 200 OK" in response[0]
    assert b"Content-Type: text/plain" in response
Example #16
0
def test_response_ok():
    foo_uri = b'http://www.host.com'
    response = server.response_ok(foo_uri)
    assert parse_response(response)[0] == '200'
def test_length():
    request = b"GET sample.txt HTTP/1.1\r\nHost:"
    uri = parse_request(request)
    response = response_ok(uri)
    assert "Content-Length: 96" in response
def test_response_ok():
    response = response_ok('a_web_page.html')
    assert "HTTP/1.1 200 OK" in response
    assert ("<p>A fine place to spend a week learning web "
            "programming!</p>" in response)
Example #19
0
def test_response_ok():
    assert server.response_ok() == b'HTTP/1.1 200 OK\r\n'