如何为Python socketserver请求处理程序编写单元测试?

时间:2011-10-11 02:59:52

标签: python unit-testing sockets tcp socketserver

如何为socketserver请求处理程序编写单元测试?我曾尝试使用以下代码,但遇到了一个问题:

import socketserver, unittest, threading

class TestServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    allow_reuse_address = True

class MyRequestHandlerTest(unittest.TestCase):
    def setUp(self):
        self.server = TestServer((HOST, PORT), MyRequestHandler)
        self.server_thread = threading.Thread(target=self.server.serve_forever)
        self.client = socket.create_connection((HOST, PORT))
        #self.server_thread.setDaemon(True)
        self.server_thread.start()

    def tearDown(self):
        self.client.close()
        self.server.shutdown()

如果我尝试使用多个测试功能,比如

    def test_foo(self):
        self.client.send(b'foo\n')
        result = self.client.recv(1024)
        self.assertEqual(b'FOO', result)

    def test_bar(self):
        self.client.send(b'bar\n')
        result = self.client.recv(1024)
        self.assertEqual(b'BAR', result)

我收到错误

socket.error: [Errno 98] Address already in use
self.server = ...行上

,即使我已将测试服务器指示为allow_reuse_address

修改:删除了我最初发布的两个错误之一,以简化问题。

1 个答案:

答案 0 :(得分:2)

它对我有用(在创建RequestHandler之后):

def tearDown(self): 
    self.client.close() 
    self.server.shutdown()
    self.server.server_close()

socketserver shutdown中的错误可能是它本身不会调用server_close