[Python-checkins] python/dist/src/Lib/test test_timeout.py,NONE,1.1 test_socket.py,1.23,1.24

gvanrossum@users.sourceforge.net gvanrossum@users.sourceforge.net
Thu, 06 Jun 2002 14:08:18 -0700


Update of /cvsroot/python/python/dist/src/Lib/test
In directory usw-pr-cvs1:/tmp/cvs-serv19155/Lib/test

Modified Files:
	test_socket.py 
Added Files:
	test_timeout.py 
Log Message:
SF patch 555085 (timeout socket implementation) by Michael Gilfix.

I've made considerable changes to Michael's code, specifically to use
the select() system call directly and to store the timeout as a C
double instead of a Python object; internally, -1.0 (or anything
negative) represents the None from the API.

I'm not 100% sure that all corner cases are covered correctly, so
please keep an eye on this.  Next I'm going to try it Windows before
Tim complains.

No way is this a bugfix candidate. :-)



--- NEW FILE: test_timeout.py ---
#!/home/bernie/src/python23/dist/src/python

import unittest

import time
import socket

class creationTestCase(unittest.TestCase):
    """Test Case for socket.gettimeout() and socket.settimeout()"""
    def setUp(self):
        self.__s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def tearDown(self):
        self.__s.close()

    def testObjectCreation(self):
        "Test Socket creation"
        self.assertEqual(self.__s.gettimeout(), None, 
            "Timeout socket not default to disable (None)")

    def testFloatReturnValue(self):
        "Test return value of getter/setter"
        self.__s.settimeout(7.345)
        self.assertEqual(self.__s.gettimeout(), 7.345, 
            "settimeout() and gettimeout() return different result")

        self.__s.settimeout(3)
        self.assertEqual(self.__s.gettimeout(), 3, 
            "settimeout() and gettimeout() return different result")

    def testReturnType(self):
        "Test return type of getter/setter"
        self.__s.settimeout(1)
        self.assertEqual(type(self.__s.gettimeout()), type(1.0),
            "return type of gettimeout() is not FloatType")

        self.__s.settimeout(3.9)
        self.assertEqual(type(self.__s.gettimeout()), type(1.0),
            "return type of gettimeout() is not FloatType")


class timeoutTestCase(unittest.TestCase):
    """Test Case for socket.socket() timeout functions"""
    def setUp(self):
        self.__s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.__addr_remote = ('www.google.com', 80)
        self.__addr_local  = ('127.0.0.1', 25339)

    def tearDown(self):
        self.__s.close()

    def testConnectTimeout(self):
        "Test connect() timeout"
        _timeout = 0.02
        self.__s.settimeout(_timeout)

        _t1 = time.time()
        self.failUnlessRaises(socket.error, self.__s.connect,
                self.__addr_remote)
        _t2 = time.time()

        _delta = abs(_t1 - _t2)
        self.assert_(_delta < _timeout + 0.5,
                "timeout (%f) is 0.5 seconds more than required (%f)"
                %(_delta, _timeout))

    def testRecvTimeout(self):
        "Test recv() timeout"
        _timeout = 0.02
        self.__s.connect(self.__addr_remote)
        self.__s.settimeout(_timeout)

        _t1 = time.time()
        self.failUnlessRaises(socket.error, self.__s.recv, 1024)
        _t2 = time.time()

        _delta = abs(_t1 - _t2)
        self.assert_(_delta < _timeout + 0.5,
                "timeout (%f) is 0.5 seconds more than required (%f)" 
                %(_delta, _timeout))

    def testAcceptTimeout(self):
        "Test accept() timeout()"
        _timeout = 2
        self.__s.settimeout(_timeout)
        self.__s.bind(self.__addr_local)
        self.__s.listen(5)

        _t1 = time.time()
        self.failUnlessRaises(socket.error, self.__s.accept)
        _t2 = time.time()

        _delta = abs(_t1 - _t2)
        self.assert_(_delta < _timeout + 0.5,
                "timeout (%f) is 0.5 seconds more than required (%f)" 
                %(_delta, _timeout))

    def testRecvfromTimeout(self):
        "Test recvfrom() timeout()"
        _timeout = 2
        self.__s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.__s.settimeout(_timeout)
        self.__s.bind(self.__addr_local)

        _t1 = time.time()
        self.failUnlessRaises(socket.error, self.__s.recvfrom, 8192)
        _t2 = time.time()

        _delta = abs(_t1 - _t2)
        self.assert_(_delta < _timeout + 0.5,
                "timeout (%f) is 0.5 seconds more than required (%f)" 
                %(_delta, _timeout))

    def testSend(self):
        "Test send() timeout"
        # couldn't figure out how to test it
        pass

    def testSendto(self):
        "Test sendto() timeout"
        # couldn't figure out how to test it
        pass

    def testSendall(self):
        "Test sendall() timeout"
        # couldn't figure out how to test it
        pass


def suite():
    suite = unittest.TestSuite()

    return suite

if __name__ == "__main__":
    unittest.main()

Index: test_socket.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_socket.py,v
retrieving revision 1.23
retrieving revision 1.24
diff -C2 -d -r1.23 -r1.24
*** test_socket.py	9 Dec 2001 08:57:46 -0000	1.23
--- test_socket.py	6 Jun 2002 21:08:16 -0000	1.24
***************
*** 110,113 ****
--- 110,114 ----
  try:
      PORT = 50007
+     msg = 'socket test\n'
      if not canfork or os.fork():
          # parent is server
***************
*** 134,144 ****
              if verbose:
                  print 'file obj:', f
              while 1:
!                 data = conn.recv(1024)
!                 if not data:
                      break
!                 if verbose:
!                     print 'received:', data
!                 conn.sendall(data)
              conn.close()
      else:
--- 135,184 ----
              if verbose:
                  print 'file obj:', f
+             data = conn.recv(1024)
+             if verbose:
+                 print 'received:', data
+             conn.sendall(data)
+ 
+             # Perform a few tests on the windows file object
+             if verbose:
+                 print "Staring _fileobject tests..."
+             f = socket._fileobject (conn, 'rb', 8192)
+             first_seg = f.read(7)
+             second_seg = f.read(5)
+             if not first_seg == 'socket ' or not second_seg == 'test\n':
+                 print "Error performing read with the python _fileobject class"
+                 os._exit (1)
+             elif verbose:
+                 print "_fileobject buffered read works"
+             f.write (data)
+             f.flush ()
+ 
+             buf = ''
              while 1:
!                 char = f.read(1)
!                 if not char:
!                     print "Error performing unbuffered read with the python ", \
!                           "_fileobject class"
!                     os._exit (1)
!                 buf += char
!                 if buf == msg:
!                     if verbose:
!                         print "__fileobject unbuffered read works"
                      break
!             if verbose:
!                 # If we got this far, write() must work as well
!                 print "__fileobject write works"
!             f.write(buf)
!             f.flush()
! 
!             line = f.readline()
!             if not line == msg:
!                 print "Error perferming readline with the python _fileobject class"
!                 os._exit (1)
!             f.write(line)
!             f.flush()
!             if verbose:
!                 print "__fileobject readline works"
! 
              conn.close()
      else:
***************
*** 150,158 ****
                  print 'child connecting'
              s.connect(("127.0.0.1", PORT))
!             msg = 'socket test'
!             s.send(msg)
!             data = s.recv(1024)
!             if msg != data:
!                 print 'parent/client mismatch'
              s.close()
          finally:
--- 190,205 ----
                  print 'child connecting'
              s.connect(("127.0.0.1", PORT))
! 
!             iteration = 0
!             while 1:
!                 s.send(msg)
!                 data = s.recv(12)
!                 if not data:
!                     break
!                 if msg != data:
!                     print "parent/client mismatch. Failed in %s iteration. Received: [%s]" \
!                           %(iteration, data)
!                 time.sleep (1)
!                 iteration += 1
              s.close()
          finally: