10

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.

1
  • Might you have another server already running on that port? Commented Oct 12, 2011 at 21:08

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.