Skip to content

Commit

Permalink
handle timestamp serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
paolo-losi committed Jul 23, 2011
1 parent 8c8857e commit ba94656
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
16 changes: 14 additions & 2 deletions stormed/serialization.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import time
import datetime
from struct import Struct
from itertools import izip

Expand Down Expand Up @@ -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 = {}
Expand All @@ -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):
Expand Down
22 changes: 20 additions & 2 deletions test/test_serialization.py
Original file line number Diff line number Diff line change
@@ -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 = \
Expand Down Expand Up @@ -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.