Mercurial > hg > Feedworm
changeset 170:f0afcd1c5656
implement a couchdb mapping field that stores a datetime instance as a JSON array
author | dirk |
---|---|
date | Fri, 09 Sep 2011 16:22:44 +0200 |
parents | 91a24f499318 |
children | 27be2a5f9c10 |
files | backend/couchdb/ListDateTimeField.py tests/couchdb/ListDateTimeFieldTests.py |
diffstat | 2 files changed, 68 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/backend/couchdb/ListDateTimeField.py Fri Sep 09 16:22:44 2011 +0200 @@ -0,0 +1,14 @@ + +from couchdb.mapping import Field +from datetime import datetime + +class ListDateTimeField(Field): + def _to_python(self, value): + if isinstance(value, list): + return datetime(*value) + return value + + def _to_json(self, value): + if isinstance(value, datetime): + return [ value.year, value.month, value.day, value.hour, value.minute, value.second ] + return value
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tests/couchdb/ListDateTimeFieldTests.py Fri Sep 09 16:22:44 2011 +0200 @@ -0,0 +1,54 @@ + +from backend.couchdb.ListDateTimeField import ListDateTimeField +from couchdb import Server +from couchdb.mapping import Document, TextField +from datetime import datetime +import unittest + +class ListDateTimeFieldTests(unittest.TestCase): + def testToJsonValid(self): + value = datetime(2011, 9, 7, 15, 21, 0) + result = ListDateTimeField()._to_json(value) + self.assertEqual([2011, 9, 7, 15, 21, 0], result) + + def testToJsonInvalid(self): + value = "this is invalid input" + result = ListDateTimeField()._to_json(value) + self.assertEqual(value, result) + + def testToPythonValid(self): + value = [2011, 9, 7, 15, 21, 0] + result = ListDateTimeField()._to_python(value) + expected = datetime(2011, 9, 7, 15, 21, 0) + self.assertEqual(expected, result) + + def testToPythonInvalid(self): + value = "this is invalid input" + result = ListDateTimeField()._to_python(value) + self.assertEqual(value, result) + + def __testRoundTrip(self): + class Dummy(Document): + title = TextField() + date = ListDateTimeField() + + server = Server() + database = server["hello-world"] + + dummy = Dummy() + dummy.title = "created from unit test" + date = datetime.now().replace(microsecond=0) + dummy.date = date + dummy.store(database) + self.assertNotEqual(None, dummy.id) + + dummy2 = Dummy.load(database, dummy.id) + self.assertNotEqual(None, dummy2) + self.assertFalse(dummy == dummy2) + self.assertEqual(date, dummy2.date) + + del database[dummy.id] + +if __name__ == "__main__": + #import sys;sys.argv = ['', 'Test.testName'] + unittest.main() \ No newline at end of file