def checkTheWorld(self):
        # Test constructors
        u = PersistentList()
        u0 = PersistentList(l0)
        u1 = PersistentList(l1)
        u2 = PersistentList(l2)

        uu = PersistentList(u)
        uu0 = PersistentList(u0)
        uu1 = PersistentList(u1)
        uu2 = PersistentList(u2)

        v = PersistentList(tuple(u))
        class OtherList:
            def __init__(self, initlist):
                self.__data = initlist
            def __len__(self):
                return len(self.__data)
            def __getitem__(self, i):
                return self.__data[i]
        v0 = PersistentList(OtherList(u0))
        vv = PersistentList("this is also a sequence")

        # Test __repr__
        eq = self.assertEqual

        eq(str(u0), str(l0), "str(u0) == str(l0)")
        eq(repr(u1), repr(l1), "repr(u1) == repr(l1)")
        eq(`u2`, `l2`, "`u2` == `l2`")

        # Test __cmp__ and __len__

        def mycmp(a, b):
            r = cmp(a, b)
            if r < 0: return -1
            if r > 0: return 1
            return r

        all = [l0, l1, l2, u, u0, u1, u2, uu, uu0, uu1, uu2]
        for a in all:
            for b in all:
                eq(mycmp(a, b), mycmp(len(a), len(b)),
                      "mycmp(a, b) == mycmp(len(a), len(b))")

        # Test __getitem__

        for i in range(len(u2)):
            eq(u2[i], i, "u2[i] == i")

        # Test __setitem__

        uu2[0] = 0
        uu2[1] = 100
        try:
            uu2[2] = 200
        except IndexError:
            pass
        else:
            raise TestFailed("uu2[2] shouldn't be assignable")

        # Test __delitem__

        del uu2[1]
        del uu2[0]
        try:
            del uu2[0]
        except IndexError:
            pass
        else:
            raise TestFailed("uu2[0] shouldn't be deletable")

        # Test __getslice__

        for i in range(-3, 4):
            eq(u2[:i], l2[:i], "u2[:i] == l2[:i]")
            eq(u2[i:], l2[i:], "u2[i:] == l2[i:]")
            for j in range(-3, 4):
                eq(u2[i:j], l2[i:j], "u2[i:j] == l2[i:j]")

        # Test __setslice__

        for i in range(-3, 4):
            u2[:i] = l2[:i]
            eq(u2, l2, "u2 == l2")
            u2[i:] = l2[i:]
            eq(u2, l2, "u2 == l2")
            for j in range(-3, 4):
                u2[i:j] = l2[i:j]
                eq(u2, l2, "u2 == l2")

        uu2 = u2[:]
        uu2[:0] = [-2, -1]
        eq(uu2, [-2, -1, 0, 1], "uu2 == [-2, -1, 0, 1]")
        uu2[0:] = []
        eq(uu2, [], "uu2 == []")

        # Test __contains__
        for i in u2:
            self.failUnless(i in u2, "i in u2")
        for i in min(u2)-1, max(u2)+1:
            self.failUnless(i not in u2, "i not in u2")

        # Test __delslice__

        uu2 = u2[:]
        del uu2[1:2]
        del uu2[0:1]
        eq(uu2, [], "uu2 == []")

        uu2 = u2[:]
        del uu2[1:]
        del uu2[:1]
        eq(uu2, [], "uu2 == []")

        # Test __add__, __radd__, __mul__ and __rmul__

        #self.failUnless(u1 + [] == [] + u1 == u1, "u1 + [] == [] + u1 == u1")
        self.failUnless(u1 + [1] == u2, "u1 + [1] == u2")
        #self.failUnless([-1] + u1 == [-1, 0], "[-1] + u1 == [-1, 0]")
        self.failUnless(u2 == u2*1 == 1*u2, "u2 == u2*1 == 1*u2")
        self.failUnless(u2+u2 == u2*2 == 2*u2, "u2+u2 == u2*2 == 2*u2")
        self.failUnless(u2+u2+u2 == u2*3 == 3*u2, "u2+u2+u2 == u2*3 == 3*u2")

        # Test append

        u = u1[:]
        u.append(1)
        eq(u, u2, "u == u2")

        # Test insert

        u = u2[:]
        u.insert(0, -1)
        eq(u, [-1, 0, 1], "u == [-1, 0, 1]")

        # Test pop

        u = PersistentList([0, -1, 1])
        u.pop()
        eq(u, [0, -1], "u == [0, -1]")
        u.pop(0)
        eq(u, [-1], "u == [-1]")

        # Test remove

        u = u2[:]
        u.remove(1)
        eq(u, u1, "u == u1")

        # Test count
        u = u2*3
        eq(u.count(0), 3, "u.count(0) == 3")
        eq(u.count(1), 3, "u.count(1) == 3")
        eq(u.count(2), 0, "u.count(2) == 0")


        # Test index

        eq(u2.index(0), 0, "u2.index(0) == 0")
        eq(u2.index(1), 1, "u2.index(1) == 1")
        try:
            u2.index(2)
        except ValueError:
            pass
        else:
            raise TestFailed("expected ValueError")

        # Test reverse

        u = u2[:]
        u.reverse()
        eq(u, [1, 0], "u == [1, 0]")
        u.reverse()
        eq(u, u2, "u == u2")

        # Test sort

        u = PersistentList([1, 0])
        u.sort()
        eq(u, u2, "u == u2")

        # Test extend

        u = u1[:]
        u.extend(u2)
        eq(u, u1 + u2, "u == u1 + u2")
Exemple #2
0
class Dispatcher:
    """ Sends commands to and receives results from a web browser. 
    
    Dispatcher: 
        _Computer Science_: A routine that controls the order in which input 
        and output devices obtain access to the processing system.
        (source: http://dictionary.reference.com/search?q=dispatcher)
    
    In Selenium, the Dispatcher class takes commands to be executed and puts 
    them in a queue for a web browser to read.
    
    When the browser reads this queue for a command to execute, it adds the 
    previous command's result to the Dispatcher's result queue.
    """
    
    def __init__(self):
        self.queue_timeout = QUEUE_TIMEOUT             
        self._commands = PersistentList()
        self._results = PersistentList()

    #
    # Command queue methods
    #
    def clearCommands(self):
        del self._commands[:]
        return 'Commands cleared'
    
    def addCommand(self, command, REQUEST=None):
        """ Add a command to the commands queue """  
        
        self._commands.append(command)     
        
        # super important to commit the change at this point...
        # In some methods (like webDriver and apiDriver), there is a later call
        # to '_p_jar.sync(), and that 
        # call would 'roll-back' this action if we didn't commit here.
        get_transaction().commit()
        
        return 'Command added'

    def getCommand(self, REQUEST=None):
        """ Retreive a command from the commands queue """
        if len(self._commands) != 0:
            response = self._commands.pop(0)
        else:
            # if the queue is empty wait to see if any commands are entered 
            # until we're forced to time out the request.
            elapsed_time = 0
            step = .5   # in seconds
            while elapsed_time <= self.queue_timeout:
                time.sleep(step)   #in seconds
                elapsed_time += step
                
                # Syncronize with the ZODB in case of any recent updates.
                # If this is being run as a unit test, we won't have an
                # attribute named "_p_jar" that we can sync()
                if not getattr(self,'_p_jar', None):
                    self._p_jar.sync()
                
                try:
                    response = self._commands.pop(0)
                    break
                except IndexError:
                    response = 'ERROR: Command queue was empty' 
                
        return response        

    def getCommandQueueSize(self, REQUEST=None):
        """ Query the size of the commands queue """
        size = len(self._commands)
        return size


    #
    # Result queue methods
    #
    def clearResults(self):
        del self._results[:]
        return 'Results cleared'
        
    def addResult(self, result, REQUEST=None):
        """ Add a result to the results queue """
        
        self._results.append(result)
        
        # super important to commit the change at this point...
        # In some methods (like webDriver and apiDriver), there is a later call
        # to '_p_jar.sync(), and that 
        # call would 'roll-back' this action if we didn't commit here.        
        get_transaction().commit()
        
        return 'Result added'

    def getResult(self, REQUEST=None):
        """ Retrieve a result from the results queue """
        if len(self._results) != 0:
            response = self._results.pop(0)
        else:
            # if the queue is empty wait to see if any results are entered 
            # until we're forced to time out the request.
            elapsed_time = 0
            step = .5   # in seconds
            while 1:
                time.sleep(step)   #in seconds
                elapsed_time += step
                
                # Syncronize with the ZODB in case of any recent updates.
                # If this is being run as a unit test, we won't have an
                # attribute named "_p_jar" that we can sync()
                if not getattr(self,'_p_jar', None):
                    self._p_jar.sync()
                    
                try:
                    response = self._results.pop(0)
                    break
                except IndexError:
                    if elapsed_time >= self.queue_timeout:
                        response = 'ERROR: Result queue was empty'
                        break
                
        return response        

    def getResultQueueSize(self, REQUEST=None):
        """ Query the size of the results queue """        
        size = len(self._results)
        return size

    #
    # Misc. methods
    #
    def setTimeout(self,timeout):
        """ Set the timeout period in seconds that a browser or driver should
        wait before timing out"""
        self.queue_timeout = timeout
        return "Timeout set to %s seconds" % timeout
            
                                   
    def webDriver(self, REQUEST=None):
        """ Gets a command from the command queue. Also, adds a result 
        to the result queue, unless the seleniumStart form paramter 
        (seleniumStart=true) is present.
        
        Note: this method is usually called from a web browser
        as "http://<server>/selenium-driver/driver"
        """
        if REQUEST:
            command_result = REQUEST.form.get('commandResult')
            selenium_start = REQUEST.form.get('seleniumStart')            
            
            # If 'seleniumStart' is a parameter on the request, 
            # it means this is the first time hitting the driver,  
            # and therefore, there is no previous result to post to 
            # the results queue.
            if selenium_start:
                self.clearResults()
            if command_result:
                self.addResult(command_result)
                                 
            return self.getCommand()                        
        else:
            return "ERROR: Missing an HTTP REQUEST"       
            
    def apiDriver(self, command_string="", REQUEST=None):
        """ Adds a command to the command queue, and gets a result 
        from the result queue.
        
        Note: this method is usually called from Python 
        source code, not a web browser."""
        if REQUEST:
            command_string = REQUEST.form.get('command_string')

        self.addCommand(command_string)
        # if test is complete, don't try retrieving a response from the browser.
        if command_string.find('testComplete') >= 0:
            return 'test complete'
        else:
            return self.getResult()