使用SimpleHTTPServer进行单元测试 [英] Using SimpleHTTPServer for unit testing

查看:96
本文介绍了使用SimpleHTTPServer进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个包装某些Web服务API的Python模块.全部都是REST,因此实现起来相对简单.

I'm writing a Python module that wraps out a certain web service API. It's all REST, so relatively straightforward to implement.

但是,在单元测试方面我发现了一个问题:由于我不运行为该模块提供服务的服务,因此我不想敲打它们,但与此同时,我需要检索数据运行我的测试.我查看了SimpleHTTPServer,这没问题.

However, I found a problem when it comes to unit testing: as I don't run the services I made this module for, I don't want to hammer them, but at the same time, I need to retrieve data to run my tests. I looked at SimpleHTTPServer, which would be OK.

我解决了部分问题,但是现在,由于我似乎无法终止线程,因此多次启动测试应用程序时遇到地址已在使用中"的问题.

I solved part of the issue I had, but now, since I can't seem to terminate the thread, I get issues with "address already in use" when launching the test application more than once.

这是一些示例代码

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文件,用于替代真实文件.程序终止后如何优雅地清理东西?

Where "index.json" is a mock JSON file I made which substitutes the real thing. How can I clean things gracefully after the program terminates?

推荐答案

尝试使用

Try using a subclass of TCPServer with allow_reuse_address set True:

class TestServer(SocketServer.TCPServer):
    allow_reuse_address = True

...
httpd = TestServer(("", PORT), handler)

这篇关于使用SimpleHTTPServer进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆