Python:单元测试基于套接字的代码? [英] Python: unit testing socket-based code?

查看:65
本文介绍了Python:单元测试基于套接字的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个使用gevent.socket进行通信的Python客户端+服务器.有什么好的方法可以测试代码的套接字级操作(例如,验证将拒绝具有无效证书的SSL连接)?还是仅spawn一台真正的服务器最简单?

编辑:由于涉及复杂的交互,我不认为幼稚"的模拟足以测试SSL组件.我说错了吗?还是有更好的方法来测试SSL内容?

解决方案

您可以轻松启动服务器,然后在测试用例中对其进行访问. gevent的自己的测试套件确实可以测试gevent的 Greenlet 那么确实生成是您应该做的.不要忘记在测试用例结束时杀死.

启动服务器并生成Greenlet是 gevent 中的快速操作,比创建新线程或进程要快得多,并且您可以轻松地为每个测试用例创建一个新服务器.只是不要忘记在不再需要服务器时立即进行清理.

我认为无需模拟任何gevent API,仅使用它就容易多了,因为服务器和客户端可以愉快地生活在同一过程中.

I'm writing a Python client+server that uses gevent.socket for communication. Are there any good ways of testing the socket-level operation of the code (for example, verifying that SSL connections with an invalid certificate will be rejected)? Or is it simplest to just spawn a real server?

Edit: I don't believe that "naive" mocking will be sufficient to test the SSL components because of the complex interactions involved. Am I wrong in that? Or is there a better way to test SSL'd stuff?

解决方案

You can easily start a server and then access it in a test case. The gevent's own test suite does exactly that for testing gevent's built-in servers.

For example:

class SimpleServer(gevent.server.StreamServer):

    def handle(self, socket, address):
        socket.sendall('hello and goodbye!')

class Test(unittest.TestCase):      

    def test(self):
        server = SimpleServer(('127.0.0.1', 0))
        server.start()
        client = gevent.socket.create_connection(('127.0.0.1', server.server_port))
        response = client.makefile().read()
        assert response == 'hello and goodbye!'
        server.stop()

Using 0 for the port value means the server will use any available port. After the server is started, the actual value chosen by bind is available as server_port attribute.

StreamServer supports SSL too, pass keyfile and certfile arguments to the constructor and it will wrap each socket with SSLObject before passing it to your handler.

If you don't use StreamServer and your server is based on Greenlet then indeed spawning it is what you should do. Don't forget to kill it at the end of the test case.

Starting a server and spawning a greenlet are fast operations in gevent, much faster than creating a new thread or process and you can easily create a new server for each test case. Just don't forget to cleanup as soon as you don't need the server anymore.

I believe there's no need to mock any of gevent API, it's much easier just to use it as servers and clients can happily live within the same process.

这篇关于Python:单元测试基于套接字的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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