Пример #1
0
def client():
    """Simple socket client that uses httpmodule to request server resource.

    1. Opens a new socket.
    2. Connects the server.
    3. Creates a valid request to send to the server.
    4. Sends the request.
    5. Receives reply from the server.
    6. Parses the reply from the server.
    7. Closes connection with the server.
    """

    # Note: Sleeps so that the socket server can boot-up before.
    time.sleep(1)

    # 1. Opens a new socket.
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 2. Connects the server.
    s.connect(("127.0.0.1", 8080))

    # 3. Creates a valid request to send to the server.
    request = Request(method="GET", target="/", protocol="HTTP/1.1")

    # 4. Sends the request.
    s.sendall(request.raw)

    # 5. Receives reply from the server.
    data = s.recv(1024)

    # 6. Parses the reply from the server.
    response = Response.parse(data)

    # 7. Closes connection with the server.
    s.close()
Пример #2
0
 def test_response_init_large(self):
     Response(
         protocol="GET",
         status=200,
         status_msg="OK",
         headers=Headers({
             "Host": "www.google.com",
             "Accept": "*/*",
             "Connection": "keep-alive",
         }),
         body=json.dumps({"hello": "world"}),
     )
Пример #3
0
    def test_response_str(self):
        parsed = Response.parse(response_raw)
        assert isinstance(parsed, Response)

        assert parsed.protocol == "HTTP/1.1"
        assert parsed.status == 200
        assert parsed.status_msg == "OK"
        assert parsed.headers == Headers({
            "Test": "Headers",
            "Host": "www.google.com",
            "Accept": "*/*",
            "Connection": "keep-alive",
        })
        assert parsed.body == '{"hello": "world"}'
Пример #4
0
def server():
    """Simple socket server that uses httpsuite to interpret and reply.

    1. Opens a new socket.
    2. Binds to 127.0.0.1:8080 and waits until new connection.
    3. Accepts connection from external source.
    4. Receive the data from the client.
    5. Parse the clients request.
    6. Interpret the request.
    7. Reply to the client.
    8. Close the connection with the client.
    """

    # 1. Opens a new socket.
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 2. Binds to 127.0.0.1:8080 and waits until new connection.
    s.bind(("127.0.0.1", 8080))
    s.listen(1)

    # 3. Accepts connection from external source.
    conn, address = s.accept()

    print("===== Connecting With New Client =====", "\n")
    print(address, "\n")

    # 4. Receive the data from the client.
    data = conn.recv(1024)

    # 5. Parse the clients request.
    request = Request.parse(data)

    print("===== Received Data From Client =====", "\n")
    print(request, "\n")

    # 6. Interpret the request.
    response = Response(protocol="HTTP/1.1", status=200, status_msg="OK")
    if request.target == "/":
        response.body = "Homepage of the microservice."
    elif request.target == "/data":
        response.body = "You are accessing the /data directory of this microservice."
    else:
        response.status = 404
        response.status_msg = "Not Found"

    print("===== Replying to Client =====", "\n")
    print(response, "\n")

    # 7. Reply to the client.
    conn.sendall(response.raw)

    print("===== Closing Connection to Client =====", "\n")

    # 8. Close the connection with the client, and the server.
    conn.close()
    s.close()
Пример #5
0
 def test_response_init_small(self):
     Response(protocol="HTTP/1.1", status=200, status_msg="OK")
Пример #6
0
 def test_init_wrong_type(self):
     with pytest.raises(TypeError):
         # pylint: disable=unexpected-keyword-arg, no-value-for-parameter
         Response(method=None, target=None, protocol=None)
Пример #7
0
            body=json.dumps({"hello": "world"}),
        )

    def test_init_wrong_type(self):
        with pytest.raises(TypeError):
            # pylint: disable=unexpected-keyword-arg, no-value-for-parameter
            Response(method=None, target=None, protocol=None)


response = Response(
    protocol="HTTP/1.1",
    status=200,
    status_msg="OK",
    headers=Headers(
        {
            "Host": "www.google.com",
            "Accept": "*/*",
            "Connection": "keep-alive",
        }
    ),
    body=json.dumps({"hello": "world"}),
)

response_raw = (
    b"HTTP/1.1 200 OK\r\n"
    b"Test: Headers\r\n"
    b"Host: www.google.com\r\n"
    b"Accept: */*\r\n"
    b"Connection: keep-alive\r\n"
    b"\r\n"
    b'{"hello": "world"}'
Пример #8
0
# 3. Connect to httpbin.org via socket.
s.connect(("httpbin.org", 80))

# 4. Send generated request to server.
s.sendall(request.raw)

# 5. Receive raw response from server.
response_raw = s.recv(4096)

# Prints the raw response.
print("====== Raw Response ======", "\n")
print(response_raw, "\n")

# 6. Parse the server's response with Response object.
response = Response.parse(response_raw)

# Prints the request and the response (pretty-print).
print("====== Request and Response ======", "\n")
print(request, "\n")
print(response, "\n")

# 7. Loads the response's body via JSON.
body = json.loads(response.body.string)

# Prints the loaded json ('dumps' for pretty-print).
print("====== Json ======", "\n")
print(json.dumps(body, indent=4))

# 8. Close socket.
s.close()
Пример #9
0
 def test_init_wrong_type(self):
     with pytest.raises(TypeError):
         Response(method=None, target=None, protocol=None)
Пример #10
0
import json

from httpsuite import Response, ENCODE

# 1. Creates the body of the request.
body = json.dumps({"hello": "world"})

# 2. Creates an HTTP response.
response = Response(
    protocol="HTTP/1.1",
    status=200,
    status_msg="OK",
    headers={
        "Host": "www.google.com",
        "Connection": "keep-alive",
        "Content-Length": len(body),
    },
    body=body,
)

# 3. Parses the equivalent response as the above.
response_parsed = Response.parse((b"HTTP/1.1 200 OK\r\n"
                                  b"Host: www.google.com\r\n"
                                  b"Connection: keep-alive\r\n"
                                  b"Content-Length: %i\r\n"
                                  b"\r\n"
                                  b"%b") % (len(body), body.encode(ENCODE)))
Пример #11
0
# ====================
#       Response
# ====================
response_headers = {
    "Host": "www.google.com",
    "Accept": "*/*",
    "Connection": "keep-alive",
    "Keep-Alive": "timeout=5, max=1000",
    "Server": "httpsuite/1.0.0",
}
response_body = json.dumps({"hello": "world"})
response = Response(
    protocol="HTTP/1.1",
    status=200,
    status_msg="OK",
    headers=response_headers,
    body=response_body,
)
response_raw = b'HTTP/1.1 200 OK\r\nHost: www.google.com\r\nAccept: */*\r\nConnection: keep-alive\r\nKeep-Alive: timeout=5, max=1000\r\nServer: httpsuite/1.0.0\r\n\r\n{"hello": "world"}'
response_first_line = b"HTTP/1.1 200 OK"

# ====================
#       Objects
# ====================
objects_headers = [request_headers, response_headers]
objects_body = [request_body, response_body]
objects = [request, response]
objects_raw = [request_raw, response_raw]
objects_first_line = [request_first_line, response_first_line]