python - 如何在 python 中模拟 http.server 以实现更快的单元测试?

标签 python unit-testing http request python-3.3

我正在尝试在本地主机上模拟一个 http 服务器以加快测试速度。

例如:

import my_module

class RequestsTestCase(unittest.TestCase):
    def setUp(self):
        # ...
        html = 'hello, world'
        my_server = MyServer(html, 8888)
        my_server.run()
        ...

    def test_my_module_request_phrase(self):
        response = my_module.get_phrase('http://localhost:8888/')
        self.assertEqual(response, 'hello, world')

使用 python 3 可以实现这样的功能吗?

最佳答案

I just wanted to test the response of a request without the need of internet (...)

没问题。您可以在运行测试的同一台主机上运行测试 http 服务器。如果您在运行测试的同一进程中运行它(在 setUp() 方法中使用 unittest 和运行测试服务器时就是这种情况),则服务器必须在单独的进程中运行线程,这样它就不会阻止您的测试。你可以看看它是如何在 urllib3 here 中完成的.

关于python - 如何在 python 中模拟 http.server 以实现更快的单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17371201/

相关文章:

unit-testing - Spock:使用可变参数模拟方法

java - 用于 Java 客户端/服务器应用程序的 HTTP 或 FTP

python - 过滤 Blaze 表中的日期

c# - 将 JSON 转换为具有值集的 C# 内联类

python - execute_async() 和 execute_concurrent() 之间的区别

java - 如何强制在每个测试方法中运行静态 block ?

actionscript-3 - AS3 POST 请求作为 GET 发送

java - 从 Java Servlet 返回字符串数组到 jQuery

python - tokenize.detect_encoding(readline) 仅在 python3 中吗?

python - 导入模块时如何防止内联代码运行?