Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write unit test for Python socketserver request handler?

How can I write unit tests for a socketserver request handler? I have tried to use the following code but have encountered 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.

like image 530
argentpepper Avatar asked Oct 11 '11 02:10

argentpepper


1 Answers

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.

like image 162
Mark Tolonen Avatar answered Oct 19 '22 20:10

Mark Tolonen