在Python中模拟HTTP服务器

pra*_*pes 9 python rest unit-testing http mocking

我正在编写REST客户端,我需要在测试中模拟HTTP服务器.什么是最合适的图书馆?如果我可以创建预期的HTTP请求并将它们与实际进行比较,那将会很棒.

Eru*_*nos 9

您还可以自己创建一个小型模拟服务器。我正在使用一个名为Flask的小型网络服务器。

import flask
app = flask.Flask(__name__)

def callback():
    return flask.jsonify(list())

app.add_url_rule("users", view_func=callback)
app.run()
Run Code Online (Sandbox Code Playgroud)

这将在http://localhost:5000/users下生成一个服务器,执行回调函数。

我创建了一个要点来提供带有关闭机制等的工作示例。 https://gist.github.com/eruvanos/f6f62edb368a20aaa880e12976620db8


cls*_*ung 8

尝试HTTPretty,Python的HTTP客户端模拟库可以帮助您专注于客户端.

  • 注意 httpretty 不是一个 Web 服务器,而是修补 python 套接字模块 (3认同)

Tom*_*zky 7

您无需使用任何外部库,只需运行临时 HTTP 服务器即可完成此操作。

例如模拟https://api.ipify.org?format=json

"""Unit tests for ipify"""

import http.server
import threading
import unittest
import urllib.request


class MockIpifyHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
    """HTTPServer mock request handler"""

    def do_GET(self):  # pylint: disable=invalid-name
        """Handle GET requests"""
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(b'{"ip":"1.2.3.45"}')

    def log_request(self, code=None, size=None):
        """Don't log anything"""


class UnitTests(unittest.TestCase):
    """Unit tests for urlopen"""

    def test_urlopen(self):
        """Test urlopen ipify"""
        server = http.server.ThreadingHTTPServer(
            ("127.0.0.127", 9999), MockIpifyHTTPRequestHandler
        )
        with server:
            server_thread = threading.Thread(target=server.serve_forever)
            server_thread.daemon = True
            server_thread.start()

            request = request = urllib.request.Request("http://127.0.0.127:9999/")
            with urllib.request.urlopen(request) as response:
                result = response.read()
            server.shutdown()

        self.assertEqual(result, b'{"ip":"1.2.3.45"}')
Run Code Online (Sandbox Code Playgroud)

我找到的替代解决方案位于/sf/answers/2445093031/