我正在尝试在本地主机上模拟一个 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/