Протестируйте http-клиент с помощью Python SimpleHTTPServer и Unittest

#python #python-3.x #python-unittest #simplehttpserver

#python #python-3.x #python-unittest #simplehttpserver

Вопрос:

У меня есть клиентская программа (написанная на другом языке), которая выполняет следующий цикл:

 GET content from a server
  

затем он воздействует на этот контент

 POST the result
  

У меня возникли проблемы с структурированием SimpleHTTPServer экземпляра и использованием его unittest для отправки команды клиенту, а затем проверки результата.

Таким образом, каждый тест будет по существу блокировать ожидание a GET , обслуживать его, затем блокировать ожидание a POST и проверять правильность отправленных данных.

ПРИМЕЧАНИЕ: я бы хотел не импортировать какие-либо библиотеки, а придерживаться как можно ближе к встроенным в python и как можно более простым.

Может кто-нибудь помочь мне с простым примером того, как я мог бы адаптировать это для достижения:

 """
Very simple HTTP server in python (Updated for Python 3.7)
Usage:
    ./PRETTYPRETTY.py -h
    ./PRETTYPRETTY.py -l localhost -p 8000
Send a GET request:
    curl http://localhost:8000
Send a HEAD request:
    curl -I http://localhost:8000
Send a POST request:
    curl -d "foo=baramp;bin=baz" http://localhost:8000
"""
import argparse
from http.server import HTTPServer, BaseHTTPRequestHandler

#imports the python encryption library
import monocypher

class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

    def _html(self, message):
        """This just generates an HTML document that includes `message`
        in the body. Override, or re-write this do do more interesting stuff.
        """
        content = message
        return content.encode("utf8")  # NOTE: must return a bytes object!

    def do_GET(self):
        self._set_headers()
        self.wfile.write(self._html("hi!"))

    def do_HEAD(self):
        self._set_headers()

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        print (post_data)
        self._set_headers()
        self.wfile.write(self._html("POST!"))


def run(server_class=HTTPServer, handler_class=S, addr="localhost", port=8000):
    server_address = (addr, port)
    httpd = server_class(server_address, handler_class)

    print(f"Starting httpd server on {addr}:{port}")
    httpd.serve_forever()


if __name__ == "__main__":

    parser = argparse.ArgumentParser(description="Run a simple HTTP server")
    parser.add_argument(
        "-l",
        "--listen",
        default="localhost",
        help="Specify the IP address on which the server listens",
    )
    parser.add_argument(
        "-p",
        "--port",
        type=int,
        default=8000,
        help="Specify the port on which the server listens",
    )
    args = parser.parse_args()
    run(addr=args.listen, port=args.port)