2 sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
4 import osrf.json, osrf.net_obj, unittest
6 class TestObject(object):
10 self.array = [1,2,3,4]
11 self.dict = {'foo': 'bar', 'key': 'value'}
16 class CheckNetworkEncoder(unittest.TestCase):
17 """Tests the NetworkEncoder JSON encoding extension"""
20 osrf.net_obj.register_hint('osrfMessage', ['threadTrace', 'locale', 'type', 'payload'], 'hash')
21 self.testo = TestObject()
22 self.ne = osrf.json.NetworkEncoder()
24 def test_connect(self):
25 test_json = self.ne.default(
26 osrf.net_obj.NetworkObject.osrfMessage({
32 self.assertEqual(test_json, {'__p': {'threadTrace': 0, 'type': 'CONNECT'}, '__c': 'osrfMessage'})
34 class CheckObjectToJSON(unittest.TestCase):
35 """Tests the osrf.json.to_json() method that converts Python objects into JSON"""
37 self.testo = TestObject()
40 test_json = osrf.json.to_json(self.testo.int)
41 self.assertEqual(test_json, '1')
43 def test_string(self):
44 test_json = osrf.json.to_json(self.testo.string)
45 self.assertEqual(test_json, '"two"')
48 test_json = osrf.json.to_json(self.testo.array)
49 self.assertEqual(test_json, '[1, 2, 3, 4]')
52 test_json = osrf.json.to_json(self.testo.dict)
53 self.assertEqual(test_json, '{"foo": "bar", "key": "value"}')
56 test_json = osrf.json.to_json(self.testo.true)
57 self.assertEqual(test_json, 'true')
60 test_json = osrf.json.to_json(self.testo.false)
61 self.assertEqual(test_json, 'false')
64 test_json = osrf.json.to_json(self.testo.null)
65 self.assertEqual(test_json, 'null')
67 class CheckJSONToObject(unittest.TestCase):
68 """Tests that the osrf.json.to_object() method converts JSON into Python objects"""
71 self.testo = TestObject()
74 test_json = osrf.json.to_object('1')
75 self.assertEqual(test_json, self.testo.int)
77 def test_string(self):
78 test_json = osrf.json.to_object('"two"')
79 self.assertEqual(test_json, self.testo.string)
82 test_json = osrf.json.to_object('[1, 2, 3, 4]')
83 self.assertEqual(test_json, self.testo.array)
86 test_json = osrf.json.to_object('{"foo": "bar", "key": "value"}')
87 self.assertEqual(test_json, self.testo.dict)
90 test_json = osrf.json.to_object('true')
91 self.assertEqual(test_json, self.testo.true)
94 test_json = osrf.json.to_object('false')
95 self.assertEqual(test_json, self.testo.false)
98 test_json = osrf.json.to_object('null')
99 self.assertEqual(test_json, self.testo.null)
101 if __name__ == '__main__':