Permalink
Browse files

handle timestamp serialization

  • Loading branch information...
1 parent 8c8857e commit ba946563584ce5422a1eb054727668e38e02763a @paolo-losi committed Jul 23, 2011
Showing with 34 additions and 4 deletions.
  1. +14 −2 stormed/serialization.py
  2. +20 −2 test/test_serialization.py
View
@@ -1,3 +1,5 @@
+import time
+import datetime
from struct import Struct
from itertools import izip
@@ -180,6 +182,15 @@ def dump_boolean(b):
else:
return chr(0)
+def dump_timestamp(dt):
+ secs = time.mktime(dt.timetuple())
+ return dump_longlong(secs)
+
+def parse_timestamp(data, offset):
+ secs, offset = parse_longlong(data, offset)
+ dt = datetime.datetime.fromtimestamp(secs)
+ return dt, offset
+
def parse_table(data, offset):
s, new_offset = parse_longstr(data, offset)
d = {}
@@ -194,10 +205,11 @@ def parse_table(data, offset):
return d, new_offset
field_type_dict = {
- 't': parse_boolean,
+ 'F': parse_table,
's': parse_shortstr,
'S': parse_longstr,
- 'F': parse_table,
+ 't': parse_boolean,
+ 'T': parse_timestamp,
}
def table2str(d):
View
@@ -1,7 +1,9 @@
import unittest
+from datetime import datetime
from stormed.util import WithFields
-from stormed.serialization import parse_method, dump_method, dump
+from stormed.serialization import parse_method, dump_method, dump, \
+ parse_timestamp, dump_timestamp
from stormed.method import connection
connection_start_payload = \
@@ -58,7 +60,23 @@ class Bunch(WithFields):
('b3', 'bit')]
o = Bunch(o1=97, b1 = False, b2 = True, b3=True)
self.assertEquals(dump(o), 'a\x06')
-
+
+class TestTimeStamp(unittest.TestCase):
+
+ def test_from_to(self):
+ dt = datetime(2011, 1, 1, 10, 5)
+ dt2, offset = parse_timestamp(dump_timestamp(dt), 0)
+ self.assertEquals(dt, dt2)
+
+ def test_from(self):
+ parsed_dt, offset = parse_timestamp('\x00\x00\x00\x00M\x1e`p', 0)
+ self.assertEquals(offset, 8)
+ self.assertEquals(parsed_dt, datetime(2011, 1, 1))
+
+ def test_to(self):
+ dt = datetime(2011, 1, 1)
+ self.assertEquals(dump_timestamp(dt), '\x00\x00\x00\x00M\x1e`p')
+
if __name__ == '__main__':
unittest.main()

0 comments on commit ba94656

Please sign in to comment.