import unittest
import datetime
import dejavu


class UnitTests(unittest.TestCase):
    
    def test_Properties(self):
        a = dejavu.Unit()
        
        self.assertEqual(a.ID, None)
        self.assertEqual(a.__class__.ID.type, int)
        a.ID = 321
        self.assertEqual(a.ID, 321)
        self.assertEqual(a.dirty, True)
        a.ID = '444'
        self.assertEqual(a.ID, 444)
        # Should remapping the property attempt to coerce all instances?
        a.set_property('ID', unicode)
        a.ID = 'my thing'
        self.assertEqual(a.ID, 'my thing')
        
        class Triggered(dejavu.UnitProperty):
            def pre(self, unit, value):
                unit.preval = value
            
            def post(self, unit, value):
                unit.postval = value
        
        class Thing(dejavu.Unit):
            Integer = dejavu.UnitProperty(int, index=True)
            String = dejavu.UnitProperty(str, hints={'Size': 0})
            Unicode = dejavu.UnitProperty(unicode)
            Datetime = Triggered(datetime.datetime)
        
        # Instance creation and population
        t = Thing(Integer=3, String='abc', Unicode=u'foo')
        self.assertEqual(t.Integer, 3)
        self.assertEqual(t.String, 'abc')
        self.assertEqual(type(t.String), str)
        self.assertEqual(t.Unicode, u'foo')
        self.assertEqual(type(t.Unicode), unicode)
        self.assertEqual(t.Datetime, None)
        
        # Index attribute
        self.assertEqual(t.__class__.Integer.index, True)
        
        # Triggers. Unit needs a sandbox or pre, post won't be called.
        t.sandbox = True
        self.assertEqual(hasattr(t, 'preval'), False)
        t.Datetime = aDate = datetime.datetime(2004, 10, 20)
        self.assertEqual(t.preval, aDate)
        self.assertEqual(t.postval, aDate)


if __name__ == "__main__":
    unittest.main()

