【发布时间】:2010-12-31 09:48:33
【问题描述】:
我正在编写一个 Python 模块,它封装了某个 Web 服务 API。这都是 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)
其中“index.json”是我制作的模拟 JSON 文件,它替代了真实的东西。程序终止后如何优雅地清理东西?
【问题讨论】:
-
SimpleHTTPServer 应该是最简单的方法。你遇到了什么问题?
-
我改写了一些东西,希望现在更清楚了。
标签: python unit-testing simplehttpserver