#! /usr/bin/python

import unittest
import sys
import random

sys.path.insert(0, '../src/lib')
import QueueDict

class QueueDictTestCase(unittest.TestCase):
    def setUp(self):
        self.N_ITEMS = 100
        self._qd = QueueDict.FeedQD()
        self._order = False
        self._qd.sort_order = self._order

        for value in xrange(self.N_ITEMS):
            for key in random.sample(xrange(self.N_ITEMS), self.N_ITEMS):
                self._qd[key] = "Item#%d" % value

    def getKeys(self):
        return self._qd.keys()

    def pickRandomKey(self, keys):
        return random.choice(keys)

    def getIndex(self, key):
        return self._qd.index(key)

    def testIndex(self):
        keys = self.getKeys()
        key = self.pickRandomKey(keys)
        self.assertEqual(keys.index(key), self._qd.index(key))

    def testKeys(self):
        self.failUnless(self.getKeys() > 0)

    def testLength(self):
        self.assertEqual (self.N_ITEMS, len(self._qd))

    def testSortOrder(self):
        self.assertEqual (self._order, self._qd.sort_order)
        self._qd.sort_order = not self._order
        self.assertNotEqual (self._order, self._qd.sort_order)

    def testFirstItem(self):
        def tfi():
            items = self._qd.items()
            front = self._qd.get_first_item()
            self.failUnless(front is not None)
            self.assertEqual(items[0][1], front)
        # normal order
        tfi()
        # reversed order
        self._qd.sort_order = not self._order
        tfi()

    def testLastItem(self):
        def lit():
            items = self._qd.items()
            back = self._qd.get_last_item()
            self.failUnless(back is not None)
            self.assertEqual(items[-1][1], back)
        # normal order
        lit()
        # reversed order
        self._qd.sort_order = not self._order
        lit()

    def testNextItem(self):
        keys = self.getKeys()
        random_key = self.pickRandomKey(keys)
        next_keyidx = self.getIndex(random_key) + 1
        next_item = self._qd.get_next_item(random_key)

        self.failUnless(next_keyidx is not None)
        self.failUnless(next_item is not None)
        self.assertEqual(self._qd.get(keys[next_keyidx]), next_item)

    def testPreviousItem(self):
        keys = self.getKeys()
        random_key = self.pickRandomKey(keys)
        prev_keyidx = self.getIndex(random_key) - 1
        prev_item = self._qd.get_previous_item(random_key)

        self.failUnless(prev_keyidx is not None)
        self.failUnless(prev_item is not None)
        self.assertEqual(self._qd.get(keys[prev_keyidx]), prev_item)


    def testNonExistentKey(self):
        # Value of a non-existent key should be None
        key = chr(int(random.random() * self.N_ITEMS))
        item = self._qd.get(key)
        self.failUnless (item is None)

def suite():
    suite = unittest.makeSuite(TestQueueDict, 'test')
    return suite

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

