00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015 """Test some utilities for working with JSON and PyMongo."""
00016
00017 import unittest
00018 import datetime
00019 import re
00020 import sys
00021 json_lib = True
00022 try:
00023 import json
00024 except ImportError:
00025 try:
00026 import simplejson as json
00027 except ImportError:
00028 json_lib = False
00029 try:
00030 import uuid
00031 should_test_uuid = True
00032 except ImportError:
00033 should_test_uuid = False
00034
00035 from nose.plugins.skip import SkipTest
00036
00037 sys.path[0:0] = [""]
00038
00039 from bson.objectid import ObjectId
00040 from bson.dbref import DBRef
00041 from bson.min_key import MinKey
00042 from bson.max_key import MaxKey
00043 from bson.timestamp import Timestamp
00044 from bson.tz_util import utc
00045 from bson.json_util import default, object_hook
00046
00047 class TestJsonUtil(unittest.TestCase):
00048
00049 def setUp(self):
00050 if not json_lib:
00051 raise SkipTest()
00052
00053 def round_tripped(self, doc):
00054 return json.loads(json.dumps(doc, default=default),
00055 object_hook=object_hook)
00056
00057 def round_trip(self, doc):
00058 self.assertEqual(doc, self.round_tripped(doc))
00059
00060 def test_basic(self):
00061 self.round_trip({"hello": "world"})
00062
00063 def test_objectid(self):
00064 self.round_trip({"id": ObjectId()})
00065
00066 def test_dbref(self):
00067 self.round_trip({"ref": DBRef("foo", 5)})
00068 self.round_trip({"ref": DBRef("foo", 5, "db")})
00069
00070
00071
00072
00073
00074
00075
00076
00077
00078
00079 def test_datetime(self):
00080
00081 self.round_trip({"date": datetime.datetime(2009, 12, 9, 15,
00082 49, 45, 191000, utc)})
00083
00084 def test_regex(self):
00085 res = self.round_tripped({"r": re.compile("a*b", re.IGNORECASE)})["r"]
00086 self.assertEqual("a*b", res.pattern)
00087 self.assertEqual(re.IGNORECASE, res.flags)
00088
00089 def test_minkey(self):
00090 self.round_trip({"m" : MinKey()})
00091
00092 def test_maxkey(self):
00093 self.round_trip({"m" : MinKey()})
00094
00095 def test_timestamp(self):
00096 res = json.dumps({"ts" : Timestamp(4, 13)}, default=default)
00097 dct = json.loads(res);
00098 self.assertEqual(dct['ts']['t'], 4)
00099 self.assertEqual(dct['ts']['i'], 13)
00100
00101 def test_uuid(self):
00102 if not should_test_uuid:
00103 raise SkipTest()
00104 self.round_trip({'uuid' : uuid.UUID('f47ac10b-58cc-4372-a567-0e02b2c3d479')})
00105
00106 if __name__ == "__main__":
00107 unittest.main()