Ein*_*nar 15 python unit-testing simplehttpserver
我正在编写一个包含某个Web服务API的Python模块.这都是REST,所以实现相对简单.
但是,我发现单元测试时遇到了问题:由于我没有运行我为此模块制作的服务,我不想敲打它们,但与此同时,我需要检索数据来运行我的试验.我看了SimpleHTTPServer,没关系.
我解决了我遇到的部分问题,但是现在,因为我似乎无法终止该线程,所以在多次启动测试应用程序时,我遇到了"已经在使用地址"的问题.
这是一些示例代码
PORT = 8001
handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), handler)
httpd_thread = threading.Thread(target=httpd.serve_forever)
httpd_thread.setDaemon(True)
httpd_thread.start()
api_data = urllib.urlopen("http://localhost:8001/post/index.json")
print "Data start:"
print json.load(api_data)
Run Code Online (Sandbox Code Playgroud)
其中"index.json"是我制作的模拟JSON文件,它取代了真实的东西.程序终止后如何优雅地清理东西?
Pet*_*sen 11
尝试使用设置为True 的TCPServerallow_reuse_address的子类:
class TestServer(SocketServer.TCPServer):
allow_reuse_address = True
...
httpd = TestServer(("", PORT), handler)
Run Code Online (Sandbox Code Playgroud)
旧线程,但这里的答案对我没有帮助,我使用的是 HTTPServer,并在每次单元测试后关闭(默认情况下 HTTPServer 设置了 allow_reuse_address = 1)。但是我在调用shutdown后仍然得到地址已经在使用的问题。我固定使用:
from BaseHTTPServer import HTTPServer
class MyHTTPServer(HTTPServer):
def shutdown(self):
self.socket.close()
HTTPServer.shutdown(self)
Run Code Online (Sandbox Code Playgroud)
不确定为什么默认情况下不会发生这种情况?可能这不是最佳选择吗?