"""
$URL: svn+ssh://sting.mems-exchange.org/repos/trunk/DurusWorks/qp/lib/test/utest_keep.py $
$Id: utest_keep.py 30557 2008-03-10 19:24:28Z rmasse $
"""
from durus.btree import BTree
from durus.persistent import Persistent
from durus.persistent_dict import PersistentDict
from qp.lib.keep import Keyed, Keep, Stamped, stamp_sorted, reverse_stamp_sorted
from qp.lib.keep import KeyCounter, GrowingRandomCounter, Counter
from sancho.utest import UTest, raises

class Test(UTest):

    def check_keep(self):
        class PKeep(Keep, Persistent):
            pass
        class PKeyed(Keyed, Persistent):
            pass
        x = PKeep(value_spec=Keyed)
        x.set_counter(Counter())
        y = PKeyed()
        z = PKeyed()
        x.add(y)
        x.add(z)
        assert list(x.iterkeys()) == [y.get_key(), z.get_key()]
        assert list(x.itervalues()) == [y, z]
        assert len(x) == 2
        x.remove(z)
        assert list(x.itervalues()) == [y]
        assert len(x) == 1
        assert list(x.iteritems()) == list(zip(x.iterkeys(), x.itervalues()))
        assert isinstance(x.get_mapping(), BTree)
        assert x.get(y.get_key()) is y
        assert x.get(1.5, 23) == 23
        raises(TypeError, x.add, None)
        bad = PKeyed()
        bad.badattr = 1
        raises(TypeError, x.add, bad)
        x = PKeep(mapping_class=PersistentDict)
        x.set_counter(Counter())
        y = PKeyed()
        z = PKeyed()
        x.add(y)
        x.add(z)
        assert list(x.iterkeys()) == [y.get_key(), z.get_key()]
        assert list(x.itervalues()) == [y, z]
        assert len(x) == 2
        x.remove(z)
        assert list(x.itervalues()) == [y]
        assert len(x) == 1
        assert list(x.iteritems()) == list(zip(x.iterkeys(), x.itervalues()))
        assert isinstance(x.get_mapping(), PersistentDict)
        GrowingRandomCounter().next()
        KeyCounter().next()
        Counter().next()

    def check_stamped(self):
        class PStamped(Persistent, Stamped):
            pass
        x = PStamped()
        y = PStamped()
        assert stamp_sorted([x, y]) == [x, y]
        assert reverse_stamp_sorted([x, y]) == [y, x]
        assert x.get_stamp() < y.get_stamp()


if __name__ == '__main__':
    Test()
