Python: How to unit test a custom HTTP request Handler?

前端 未结 3 1265
自闭症患者
自闭症患者 2021-02-20 17:12

I have a custom HTTP request handler that can be simplified to something like this:

# Python 3:
from http import server

c         


        
3条回答
  •  执笔经年
    2021-02-20 17:50

    Here's one approach I came up with to mock the server. Note that this should be compatible with both Python 2 and python 3. The only issue is that I can't find a way to access the result of the GET request, but at least the test will catch any exceptions it comes across!

    try:
        # Python 2.x
        import BaseHTTPServer as server
        from StringIO import StringIO as IO
    except ImportError:
        # Python 3.x
        from http import server
        from io import BytesIO as IO
    
    
    class MyHandler(server.BaseHTTPRequestHandler):
        """Custom handler to be tested"""
        def do_GET(self):
            # print just to confirm that this method is being called
            print("executing do_GET") # just to confirm...
    
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
    
            # Here's where all the complicated logic is done to generate HTML.
            # For clarity here, replace with a simple stand-in:
            html = "

    hello world

    " self.wfile.write(html.encode()) def test_handler(): """Test the custom HTTP request handler by mocking a server""" class MockRequest(object): def makefile(self, *args, **kwargs): return IO(b"GET /") class MockServer(object): def __init__(self, ip_port, Handler): handler = Handler(MockRequest(), ip_port, self) # The GET request will be sent here # and any exceptions will be propagated through. server = MockServer(('0.0.0.0', 8888), MyHandler) test_handler()

提交回复
热议问题