Search code examples
pythonunit-testingsocketspython-unittest

Python Client-Server Script Unit Testing Error


I have client and server scripts that serves/reads some data.

When i tried to write unit tests with using PyUnit, there raises a error that i cannot reason it.

Here is the relevant code snippet:

class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
    #some set up operations

def testRecieve(self):
    s = socket.socket()   
    s.connect((FEED_SERVER_HOST, FEED_SERVER_PORT))
    sock = socket.socket()    
    #some recieve operations        
    s.close()

 # When i write this code snippet below, i get error: [Errno 98] Address already in use
error. I tried closing 's' socket in tearDown function but still same error raising.

    def testAnotherRecieve(self):
        sock = socket.socket() # Results ERRNO 98.

As summary, i cannot create second socket in the unittest class. What may cause this error?


Solution

  • Looking at the socket docs for close(), the socket's probably not closed by the time the second test starts up:

    close() releases the resource associated with a connection but does not necessarily close the connection immediately. If you want to close the connection in a timely fashion, call shutdown() before close().