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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With