def test_parse_request_not_http_1_1(): request = [] request.append(b'GET /path/to/URI HTTP/1.0') request.append(b'Host: www.google.com') request = (b'\r\n').join(request) with pytest.raises(NotImplementedError): server.parse_request(request)
def test_parse_request_rejects_non_http_1_1(): with pytest.raises(Exception): server.parse_request( b"GET / HTTP/1.0\r\n" b"Host: http://example.com\r\n" b"\r\n" )
def test_parse_request_not_get(): request = [] request.append(b'POST /path/to/URI HTTP/1.1') request.append(b'Host: www.google.com') request = (b'\r\n').join(request) with pytest.raises(TypeError): server.parse_request(request)
def test_parse_request_rejects_non_get(): with pytest.raises(NotImplementedError): server.parse_request( b"POST / HTTP/1.1\r\n" b"Host: http://example.com\r\n" b"\r\n" )
def test_request_host(): """Test that server throws IndexError when no headers are included.""" from server import parse_request test_str = """ GET /favicon.ico HTTP/1.1\r\n""" with pytest.raises(IndexError): parse_request(test_str)
def test_parse_request_rejects_absent_host_header(): with pytest.raises(ValueError): server.parse_request( b"GET / HTTP/1.1\r\n" b"Some bullshit header\r\n" b"Another shitty header\r\n" b"\r\n" )
def test_parse_req_host(): """Test that parser raises AttributeError when Host header is missing.""" from server import parse_request request_str = """ GET /favicon.ico HTTP/1.1\r\n Something\r\n """ with pytest.raises(AttributeError): parse_request(request_str)
def test_parse_req_protocol(): """Test that parser raises ValueError on improper HTTP protocol.""" from server import parse_request request_str = """ GET /favicon.ico HTTP/1.0\r\n Host: 111.1.1.1:4000\r\n """ with pytest.raises(ValueError): parse_request(request_str)
def test_parse_req_method(): """Test that parser raises TypeError on improper request method.""" from server import parse_request request_str = """ POST /favicon.ico HTTP/1.1\r\n Host: 111.1.1.1:4000\r\n """ with pytest.raises(TypeError): parse_request(request_str)
def test_request_header_host(): """Test that server throws RequestError when host header is not included.""" from server import parse_request from server import RequestError test_str = """ GET /favicon.ico HTTP/1.1\r\n Content-Type: text/html""" with pytest.raises(RequestError): parse_request(test_str)
def test_parse_request(cli_request, error, msg, uri): """Test that parse_request returns the URI or raises appropriate error.""" from server import parse_request if error: with pytest.raises(error) as e: parse_request(cli_request) assert e.args[0] == msg else: assert parse_request(cli_request) == uri
def test_request_method(): """Test that server throws RequestError when method is not supported.""" from server import parse_request from server import RequestError test_str = """ POST /favicon.ico HTTP/1.1\r\n Host: 111.1.1.1:4000\r\n""" with pytest.raises(RequestError): parse_request(test_str)
def test_request_protocol(): """Test that server throws RequestError when protocol is incorrect.""" from server import parse_request from server import RequestError test_str = """ GET /favicon.ico HTTP/1.0\r\n Host: 111.1.1.1:4000\r\n""" with pytest.raises(RequestError): parse_request(test_str)
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
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 test_parse_request_uri(): """Test that parse_request method properly extracts URI from request.""" from server import parse_request test_str = """ GET /favicon.ico HTTP/1.1\r\n Host: 111.1.1.1:4000\r\n""" assert parse_request(test_str) == "/favicon.ico"
def test_parse_request_valid_request(): request = [] request.append(b'GET /path/to/URI HTTP/1.1') request.append(b'Host: www.google.com') request.append(b'') request = (b'\r\n').join(request) response = server.parse_request(request) assert response == b'/path/to/URI'
def test_parse_request_returns_validated_request(): valid_request = ( b"GET /heres/the/URI HTTP/1.1\r\n" b"Host: www.example.com\r\n" b"\r\n" b"blah blah some kind of body\r\n" b"\r\n" ) assert b"/heres/the/URI" == server.parse_request(valid_request)
def test_request_permitted(self): message = """GET /sample.txt HTTP/1.1\r\n \Host: www.example.com \r\n \<CRLF>""" body, content_type = parse_request(message) response = build_response(body, content_type) expected_text = """This is a very simple text file. Just to show that we can server it up. It is three lines long.""" self.assertIn(expected_text, response)
def test_parse_req(): """Test parser for proper capture of URI.""" from server import parse_request request_str = """ GET /favicon.ico HTTP/1.1\r\n Host: 111.1.1.1:4000\r\n """ request_split = request_str.split() uri = request_split[1] assert parse_request(request_str) == uri
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()
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_parse_request_format(): """Test parse_request returns correct responses.""" from server import parse_request assert parse_request(REQUESTS_RESPONSES[3][0]) == REQUESTS_RESPONSES[3][1]
def test_request_parse_invalid_number_of_lines(): """Test if not three lines in request, raises ValueError.""" req = b'GET /index.html HTTP/1.1\r\n\ Host: www.example.com\r\n' with pytest.raises(ValueError): parse_request(req)
def test_parse_request_return(): """Test parse request for content and type.""" from server import parse_request req = b"GET /images HTTP/1.1\r\nHost: www.example.com\r\n\r\n" assert parse_request(req).startswith(b"HTTP/1.1 200 OK")
def test_parse_request_400_bad_request(): """Check if URI is returned from parse request function.""" from server import parse_request req = b"GET /index.html HTTP/1.1\r\nHist: www.example.com\r\n" assert parse_request(req).startswith(b'HTTP/1.1 400')
def test_parse_request(msg, result): """Parse a good HTTP request.""" from server import parse_request assert parse_request( 'GET {} HTTP/1.1\r\nHost: localhost\r\n\r\n'.format(msg)) == result
def test_parse_method_2(): """Test that server checks HTTP requests for Host header.""" from server import parse_request with pytest.raises(LookupError): argument = "GET /path/to/index.html HTTP/1.1\r\nHoot: www.mysite1.com:80\r\n\r\n" parse_request(argument)
def test_parse_method_0(): """Test that server checks HTTP requests for GET method.""" from server import parse_request with pytest.raises(NameError): argument = "BLET /path/to/index.html HTTP/1.1\r\nHost: www.mysite1.com:80\r\n\r\n" parse_request(argument)
def test_parse_request_correct(): """Test for 200 response if correct header used.""" from server import parse_request assert parse_request(HEADER) == '/src/server.py'
def test_parse_request_good(requests, expects): request_text = server.CRLF.join(requests['good']) assert server.parse_request(request_text) == expects['good']
def test_parse_request_wrong_http(requests, expects): request_text = server.CRLF.join(requests['wrong_http']) with pytest.raises(expects['wrong_http']): server.parse_request(request_text)
def test_parse_request_value_error(request): """Test parse_request with invalid request.""" from server import parse_request with pytest.raises(ValueError): parse_request(request)
def test_parse_no_host_req(): """Test parse function returns proper error.""" try: parse_request('GET /URI HTTP/1.1') except ValueError: pass
def test_parse_request_raises_value_error(): """Test that value error gets raised.""" from server import parse_request with pytest.raises(ValueError): parse_request(b"PUT /http-server/src/server.py HTTP/1.1\r\n\ HOST: 127.0.0.1:5000")
def test_parse_request_raises_index_error(): """Test that index error gets raised.""" from server import parse_request with pytest.raises(IndexError): parse_request(b"GET /http-server/src/server.py HTTP/1.0\r\n\ HOST: 127.0.0.1:5000")
def test_parse_request_raises_key_error(): """Test that key error gets raised.""" from server import parse_request with pytest.raises(KeyError): parse_request(b"GET /http-server/src/server.py HTTP/1.1\r\n")
def test_server_parse_req_bad_get(message): """If GET is bad, parse request function returns error code 405.""" with pytest.raises(ValueError): parse_request(message)
def test_bad_http_request(args, result, http_error_code): from server import parse_request with pytest.raises(result): parse_request(args)
def test_parse_method_1(): """Test that server checks HTTP requests for correct HTTP version.""" from server import parse_request with pytest.raises(AttributeError): argument = "GET /path/to/index.html HTTP/1.0\r\nHost: www.mysite1.com:80\r\n\r\n" parse_request(argument)
def test_good_http_request(args, result): from server import parse_request assert parse_request(args) == result
def test_good_request(): """Test that a well formed request gets path returned from parsing to a good request""" from server import parse_request request = "GET sample.txt HTTP/1.1\r\nHost: www.mysite1.com:80\r\n\r\n" assert parse_request(request) == 'sample.txt'
def test_parse_request_valid_input(): """That that a valid request returns the URI.""" from server import parse_request req = 'GET /path/to/index.html HTTP/1.1\r\nHost: /sample.txt\r\n\r\n' assert parse_request(req) == '/path/to/index.html'
def test_parse_request_errors(header, error): """Test if correct errors get raised for different headers.""" from server import parse_request with pytest.raises(error): parse_request(header)
def test_parse_request_with_method_not_allowed(): """That that a request using a method other than GET raises an error.""" from server import parse_request req = 'PUT /path/to/index.html HTTP/1.1\r\nHost: /sample.txt\r\n\r\n' with pytest.raises(ValueError): parse_request(req)
def test_parse_request_505_error_bad_protocol(): """Check if protocol is returned from parse request function.""" from server import parse_request req = b"GET /index.html HTTP/2.1\r\nHost: www.example.com\r\n\r\n" assert parse_request(req).startswith(b'HTTP/1.1 505')
def test_parse_request_with_wrong_protocol(): """That that request with protocol other than HTTP/1.1 raises an error.""" from server import parse_request req = 'GET /path/to/index.html HTTP/1.0\r\nHost: /sample.txt\r\n\r\n' with pytest.raises(ValueError): parse_request(req)
def test_parse_request_missing_host_header(): """That that request without a host header raises an error.""" from server import parse_request req = 'GET /path/to/index.html HTTP/1.1\r\nHost /sample.txt\r\n\r\n' with pytest.raises(ValueError): parse_request(req)
def test_server_parse_request_ok(message, result): """Test parse request function receives properly formatted request.""" assert parse_request(message) == result
def test_valid_parse_http_request(): """Test the parse_request accepts valid GET http request.""" req = b'GET /index.html HTTP/1.1\r\n\ Host: www.example.com\r\n\ \r\n' assert parse_request(req) == b'/index.html'
def test_server_parse_req_bad_len(message): """Test the length function in the parse request function.""" with pytest.raises(ValueError): parse_request(message)
def test_parse_request_ok(): """Test parse_request with valid request.""" from server import parse_request req = b"GET www.gremlins.com HTTP/1.1\r\nHost: me\r\n\r\n" assert parse_request(req) == b'www.gremlins.com'
def test_parse_request_raises_attribute_error(): """Test that attribute error gets raised.""" from server import parse_request with pytest.raises(AttributeError): parse_request(b"GET /htp-server/src/server.py HTTP/1.1\r\n\ HOST: 127.0.0.1:5000")