"""
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/lib/test/utest_sort.py $
$Id: utest_sort.py 31117 2008-09-16 14:55:12Z dbinger $
"""

from sancho.utest import UTest
from dulcinea.sort import str_sort, lexical_sort
from dulcinea.sort import attr_sort, method_sort

class Thing:
    counter = 0

    def __init__(self, name):
        self.name = name
        Thing.counter += 1
        self.id = "T-%03d" % Thing.counter

    def __str__(self):
        return self.name

    def __lt__(self, other):
        return self.id < other.id

    def get_id(self):
        return self.id


def gen(*args):
    for arg in args:
        yield arg


class SortTest (UTest):

    def check_instances(self):
        thing1 = Thing("bob")
        thing2 = Thing("Tim")
        thing3 = Thing("123-abc")
        things = [thing2, thing1, thing3]
        assert str_sort(things) == [thing3, thing2, thing1]
        assert lexical_sort(gen(thing1, thing2, thing3)) == [
            thing3, thing1, thing2]
        assert attr_sort(things, 'id') == [thing1, thing2, thing3]
        assert attr_sort(things, 'name') == [thing3, thing2, thing1]
        assert method_sort(gen(thing2, thing1, thing3), 'get_id') == [
            thing1, thing2, thing3]
        def fun_get_id(x):
            return x.get_id()
        assert sorted(gen(thing2, thing1, thing3), key=fun_get_id) == [
            thing1, thing2, thing3]

if __name__ == "__main__":
    SortTest()
