Python/BLIPConnectionTest.py
author Jens Alfke <jens@mooseyard.com>
Wed Jun 04 17:11:20 2008 -0700 (2008-06-04)
changeset 13 84c2d38f924c
child 14 bb5faa9995d5
permissions -rw-r--r--
Python implementation much improved. Can send requests now. Fully interoperable with Obj-C implementation's test cases.
     1 #!/usr/bin/env python
     2 # encoding: utf-8
     3 """
     4 BLIPConnectionTest.py
     5 
     6 Created by Jens Alfke on 2008-06-04.
     7 This source file is test/example code, and is in the public domain.
     8 """
     9 
    10 from BLIP import Connection, OutgoingRequest, kOpening
    11 
    12 import asyncore
    13 from cStringIO import StringIO
    14 from datetime import datetime
    15 import logging
    16 import random
    17 import unittest
    18 
    19 
    20 kSendInterval = 2.0
    21 
    22 def randbool():
    23     return random.randint(0,1) == 1
    24 
    25 
    26 class BLIPConnectionTest(unittest.TestCase):
    27 
    28     def setUp(self):
    29         self.connection = Connection( ('localhost',46353) )
    30    
    31     def sendRequest(self):
    32         size = random.randint(0,32767)
    33         io = StringIO()
    34         for i in xrange(0,size):
    35             io.write( chr(i % 256) )
    36         body = io.getvalue()
    37         io.close
    38     
    39         req = OutgoingRequest(self.connection, body,{'Content-Type': 'application/octet-stream',
    40                                                      'User-Agent':  'PyBLIP',
    41                                                      'Date': datetime.now(),
    42                                                      'Size': size})
    43         req.compressed = randbool()
    44         req.urgent     = randbool()
    45         req.response.onComplete = self.gotResponse
    46         return req.send()
    47     
    48     def gotResponse(self, response):
    49         logging.info("Got response!: %s",response)
    50         request = response.request
    51         assert response.body == request.body
    52 
    53     def testClient(self):
    54         lastReqTime = None
    55         nRequests = 0
    56         while nRequests < 10:
    57             asyncore.loop(timeout=kSendInterval,count=1)
    58             
    59             now = datetime.now()
    60             if self.connection.status!=kOpening and not lastReqTime or (now-lastReqTime).seconds >= kSendInterval:
    61                 lastReqTime = now
    62                 if not self.sendRequest():
    63                     logging.warn("Couldn't send request (connection is probably closed)")
    64                     break;
    65                 nRequests += 1
    66     
    67     def tearDown(self):
    68         self.connection.close()
    69 
    70 if __name__ == '__main__':
    71     logging.basicConfig(level=logging.INFO)
    72     unittest.main()