我应该如何为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
,但仍然存在问题。