如何对自定义HTTP请求处理程序进行单元测试

如何对自定义HTTP请求处理程序进行单元测试

本文介绍了Python:如何对自定义HTTP请求处理程序进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义HTTP请求处理程序,可以将其简化为以下形式:

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

# Python 3:
from http import server

class MyHandler(server.BaseHTTPRequestHandler):
    def do_GET(self):
        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 = "<html><p>hello world</p></html>"

        self.wfile.write(html.encode())

我想对这个处理程序进行单元测试(即确保我的do_GET无例外地执行),而无需实际启动Web服务器.有什么轻巧的方法可以模拟SimpleHTTPServer以便我可以测试此代码?

I'd like to unit-test this handler (i.e. make sure that my do_GET executes without an exception) without actually starting a web server. Is there any lightweight way to mock the SimpleHTTPServer so that I can test this code?

推荐答案

这是我想出的模拟服务器的一种方法.请注意,这应该与Python 2和python 3兼容.唯一的问题是我找不到一种方法来访问GET请求的结果,但是至少该测试将捕获遇到的任何异常!

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 = "<html><p>hello world</p></html>"

        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()

这篇关于Python:如何对自定义HTTP请求处理程序进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:11