开发者

How to write unit test for Python socketserver request handler?

开发者 https://www.devze.com 2023-04-12 16:11 出处:网络
How can I write unit tests for a socketserver request handler? I have tried to use the following code but have enco开发者_如何学Gountered a problem:

How can I write unit tests for a socketserver request handler? I have tried to use the following code but have enco开发者_如何学Gountered a problem:

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()

If I try to use multiple test functions, like this

    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)

I get the error

socket.error: [Errno 98] Address already in use

on the line self.server = ..., even though I instructed the test server to allow_reuse_address.

Edit: removed one of the two errors I had originally posted in order to simplify the question.


It worked for me (after creating a RequestHandler) with:

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

It may be a bug in socketserver shutdown that it doesn't call server_close itself.

0

精彩评论

暂无评论...
验证码 换一张
取 消