def test_datetime_inside_int_keys(self): t = datetime.time(hour=10) s = jsonstruct.encode({1: t, 2: t}) d = jsonstruct.decode(s) self.assertEqual(d["1"], d["2"]) self.assertTrue(d["1"] is d["2"]) self.assertTrue(isinstance(d["1"], datetime.time))
def test_cyclical(self): """Test that we can pickle cyclical data structure This test is ensures that we can reference objects which first appear within a list (in other words, not a top-level object or attribute). Later children will reference that object through its "_parent" field. This makes sure that we handle this case correctly. """ document = Document('My Document') section1 = Section('Section 1') section2 = Section('Section 2') question1 = Question('Question 1') question2 = Question('Question 2') question3 = Question('Question 3') question4 = Question('Question 4') document.add_child(section1) document.add_child(section2) section1.add_child(question1) section1.add_child(question2) section2.add_child(question3) section2.add_child(question4) pickled = jsonstruct.encode(document) unpickled = jsonstruct.decode(pickled) self.assertEqual(str(document), str(unpickled))
def test_datetime_inside_int_keys(self): t = datetime.time(hour=10) s = jsonstruct.encode({1:t, 2:t}) d = jsonstruct.decode(s) self.assertEqual(d["1"], d["2"]) self.assertTrue(d["1"] is d["2"]) self.assertTrue(isinstance(d["1"], datetime.time))
def test_json(self): pickled = jsonstruct.encode(self.obj) self.assertEqual(self.expected_json, pickled) unpickled = jsonstruct.decode(self.expected_json) self.assertEqual(self.obj.name, unpickled.name) self.assertEqual(type(self.obj), type(unpickled))
def assertEncodeDecode(self, expected_pickled): pickled = jsonstruct.encode(SAMPLE_DATA) self.assertEqual(expected_pickled, pickled) unpickled = jsonstruct.decode(pickled) self.assertEqual(SAMPLE_DATA['things'][0].name, unpickled['things'][0].name)
def test_recursive(self): """create a recursive structure and test that we can handle it """ parent = Thing('parent') child = Thing('child') child.sibling = Thing('sibling') parent.self = parent parent.child = child parent.child.twin = child parent.child.parent = parent parent.child.sibling.parent = parent cloned = jsonstruct.decode(jsonstruct.encode(parent)) self.assertEqual(parent.name, cloned.name) self.assertEqual(parent.child.name, cloned.child.name) self.assertEqual(parent.child.sibling.name, cloned.child.sibling.name) self.assertEqual(cloned, cloned.child.parent) self.assertEqual(cloned, cloned.child.sibling.parent) self.assertEqual(cloned, cloned.child.twin.parent) self.assertEqual(cloned.child, cloned.child.twin)
def status(): """ Returns the current status of the sentiment analysis (id, status, tweets_analyzed, avg_mood, pos_tweets, neg_tweets, neu_tweets). """ tweetCtrl = TweetController(server) ret = jsonstruct.encode(tweetCtrl.get_status()) return Response(response=ret, status=200, mimetype="application/json")
def test_object_dict_keys(self): """Test that we handle random objects as keys. """ thing = Thing('random') pickled = jsonstruct.encode({thing: True}) unpickled = jsonstruct.decode(pickled) self.assertEqual(unpickled, {u('Thing("random")'): True})
def _roundtrip(self, obj): """ pickle and then unpickle object, then assert the new object is the same as the original. """ pickled = jsonstruct.encode(obj) unpickled = jsonstruct.decode(pickled) self.assertEquals(obj, unpickled)
def save_tweets(self): """ Saves in memory tweets to given save save_location. """ print("Saving tweets to tweets.json") f = open(os.path.dirname(__file__) + self.save_location, "w") f.write(jsonstruct.encode(self.tweets)) f.close()
def root(request): param = {"user_id": request.user.user_id} case_info = main_service.last_case(param) context = {"case_info": jsonstruct.encode(case_info)} template = loader.get_template("main/root.html") return HttpResponse(template.render(context, request))
def test_datetime_dict_keys(self): """Test that we handle datetime objects as keys. We do not model this presently, so ensure that we at least convert those tuples into repr strings. """ pickled = jsonstruct.encode({datetime.datetime(2008, 12, 31): True}) unpickled = jsonstruct.decode(pickled) self.assertTrue(unpickled['datetime.datetime(2008, 12, 31, 0, 0)'])
def test_list_item_reference(self): thing = Thing('parent') thing.child = Thing('child') thing.child.refs = [thing] encoded = jsonstruct.encode(thing) decoded = jsonstruct.decode(encoded) self.assertEqual(id(decoded.child.refs[0]), id(decoded))
def test_repr_using_jsonstruct(self): thing = ObjWithJsonStructRepr() thing.child = ObjWithJsonStructRepr() thing.child.parent = thing encoded = jsonstruct.encode(thing) decoded = jsonstruct.decode(encoded) self.assertEqual(id(decoded), id(decoded.child.parent))
def test_list_of_objects(self): """Test that objects in lists are referenced correctly""" a = Thing('a') b = Thing('b') pickled = jsonstruct.encode([a, b, b]) unpickled = jsonstruct.decode(pickled) self.assertEqual(unpickled[1], unpickled[2]) self.assertEqual(type(unpickled[0]), Thing) self.assertEqual(unpickled[0].name, 'a') self.assertEqual(unpickled[1].name, 'b') self.assertEqual(unpickled[2].name, 'b')
def test_set_preferred_backend_allows_magic(self): """Tests that we can use the pluggable backends magically """ backend = 'os.path' jsonstruct.load_backend(backend, 'split', 'join', AttributeError) jsonstruct.set_preferred_backend(backend) slash_hello, world = jsonstruct.encode('/hello/world') jsonstruct.remove_backend(backend) self.assertEqual(slash_hello, '/hello') self.assertEqual(world, 'world')
def test_namedtuple_roundtrip(self): old_nt = NamedTuple(0, 1, 2) encoded = jsonstruct.encode(old_nt) new_nt = jsonstruct.decode(encoded) self.assertEqual(type(old_nt), type(new_nt)) self.assertTrue(old_nt is not new_nt) self.assertEqual(old_nt.a, new_nt.a) self.assertEqual(old_nt.b, new_nt.b) self.assertEqual(old_nt.c, new_nt.c) self.assertEqual(old_nt[0], new_nt[0]) self.assertEqual(old_nt[1], new_nt[1]) self.assertEqual(old_nt[2], new_nt[2])
def test_deque_roundtrip(self): """Make sure we can handle collections.deque""" old_deque = collections.deque([0, 1, 2]) encoded = jsonstruct.encode(old_deque) new_deque = jsonstruct.decode(encoded) self.assertNotEqual(encoded, 'nil') self.assertEqual(old_deque[0], 0) self.assertEqual(new_deque[0], 0) self.assertEqual(old_deque[1], 1) self.assertEqual(new_deque[1], 1) self.assertEqual(old_deque[2], 2) self.assertEqual(new_deque[2], 2)
def test_ordered_dict(self): if sys.version_info < (2, 7): return d = collections.OrderedDict() d.update(c=3) d.update(a=1) d.update(b=2) encoded = jsonstruct.encode(d) decoded = jsonstruct.decode(encoded) self.assertEqual(d, decoded)
def test_tuple_dict_keys(self): """Test that we handle dictionaries with tuples as keys. We do not model this presently, so ensure that we at least convert those tuples to repr strings. TODO: handle dictionaries with non-stringy keys. """ pickled = jsonstruct.encode({(1, 2): 3, (4, 5): {(7, 8): 9}}) unpickled = jsonstruct.decode(pickled) subdict = unpickled['(4, 5)'] self.assertEqual(unpickled['(1, 2)'], 3) self.assertEqual(subdict['(7, 8)'], 9)
def test_tuple_dict_keys(self): """Test that we handle dictionaries with tuples as keys. We do not model this presently, so ensure that we at least convert those tuples to repr strings. TODO: handle dictionaries with non-stringy keys. """ pickled = jsonstruct.encode({(1, 2): 3, (4, 5): { (7, 8): 9 }}) unpickled = jsonstruct.decode(pickled) subdict = unpickled['(4, 5)'] self.assertEqual(unpickled['(1, 2)'], 3) self.assertEqual(subdict['(7, 8)'], 9)
def test_reference_to_list(self): thing = Thing('parent') thing.a = [1] thing.b = thing.a thing.b.append(thing.a) thing.b.append([thing.a]) encoded = jsonstruct.encode(thing) decoded = jsonstruct.decode(encoded) self.assertEqual(decoded.a[0], 1) self.assertEqual(decoded.b[0], 1) self.assertEqual(id(decoded.a), id(decoded.b)) self.assertEqual(id(decoded.a), id(decoded.a[1])) self.assertEqual(id(decoded.a), id(decoded.a[2][0]))
def test_unicode_mixin(self): obj = UnicodeMixin('test') self.assertEqual(type(obj), UnicodeMixin) self.assertEqual(unicode(obj), u('test')) # Encode into JSON content = jsonstruct.encode(obj) # Resurrect from JSON new_obj = jsonstruct.decode(content) new_obj += ' passed' self.assertEqual(unicode(new_obj), u('test passed')) self.assertEqual(type(new_obj), UnicodeMixin) self.assertTrue(new_obj.ok())
def test_defaultdict_roundtrip(self): """Make sure we can handle collections.defaultdict(list)""" # setup defaultdict = collections.defaultdict(list) defaultdict['a'] = 1 defaultdict['b'].append(2) defaultdict['c'] = collections.defaultdict(dict) # jsonstruct work your magic encoded = jsonstruct.encode(defaultdict) newdefaultdict = jsonstruct.decode(encoded) # jsonstruct never fails self.assertEqual(newdefaultdict['a'], 1) self.assertEqual(newdefaultdict['b'], [2]) self.assertEqual(type(newdefaultdict['c']), collections.defaultdict) self.assertEqual(defaultdict.default_factory, list) self.assertEqual(newdefaultdict.default_factory, list)
def login(request): result = "F" access_token = auth_service.login(request) if access_token: result = "S" return_data = {"result": result} response = HttpResponse(jsonstruct.encode(return_data), \ content_type=HttpRequest.CONTENT_TYPE_JSON_UTF8) if access_token: response["Authorization"] = access_token return response
def prev_or_next(request): json_payload = json.loads(request.body) case_info = json_payload["case_info"] case_info.update({"user_id": request.user.user_id}) query = json_payload["query"] query.update({"user_id": request.user.user_id}) if "greater_than" in query: case_info = main_service.next_case(case_info, query) elif "less_than" in query: case_info = main_service.prev_case(case_info, query) context = {"case_info": case_info} return HttpResponse(jsonstruct.encode(context), content_type=HttpRequest.CONTENT_TYPE_JSON_UTF8)
def test_encode(self): pickled = jsonstruct.encode(self.obj) self.assertEqual(self.expected_json, pickled)
def __repr__(self): return jsonstruct.encode(self)
def test_object_with_datetime(self): test_obj = ObjWithDate() json = jsonstruct.encode(test_obj) test_obj_decoded = jsonstruct.decode(json) self.assertEqual(test_obj_decoded.data['ts'], test_obj_decoded.data_ref['ts'])
def test_newstyleslots_with_children(self): obj = ThingWithSlots(Thing('a'), Thing('b')) jsonstr = jsonstruct.encode(obj) newobj = jsonstruct.decode(jsonstr) self.assertEqual(newobj.a.name, 'a') self.assertEqual(newobj.b.name, 'b')
def test_newstyleslots(self): obj = ThingWithSlots(True, False) jsonstr = jsonstruct.encode(obj) newobj = jsonstruct.decode(jsonstr) self.assertTrue(newobj.a) self.assertFalse(newobj.b)
def current(request): param = {"user_id": request.user.user_id} case_info = main_service.last_case(param) return HttpResponse(jsonstruct.encode(case_info), content_type=HttpRequest.CONTENT_TYPE_JSON_UTF8)
def test_tuple_roundtrip(self): data = (1,2,3) newdata = jsonstruct.decode(jsonstruct.encode(data)) self.assertEqual(data, newdata)
def test_unicode_dict_keys(self): pickled = jsonstruct.encode({'é'.decode('utf-8'): 'é'.decode('utf-8')}) unpickled = jsonstruct.decode(pickled) self.assertEqual(unpickled['é'.decode('utf-8')], 'é'.decode('utf-8')) self.assertTrue('é'.decode('utf-8') in unpickled)
def logout(request): auth_service.logout(request) return HttpResponse(jsonstruct.encode({}), content_type=HttpRequest.CONTENT_TYPE_JSON_UTF8)
def test(self): pickled = jsonstruct.encode(self.doc) unpickled = jsonstruct.decode(pickled) self.assertEquals(self.doc['feed']['title'], unpickled['feed']['title'])
def test_list_roundtrip(self): data = [1,2,3] newdata = jsonstruct.decode(jsonstruct.encode(data)) self.assertEqual(data, newdata)
def test_encode_notunpicklable(self): pickled = jsonstruct.encode(self.obj, unpicklable=False) self.assertEqual('{"name": "A name", "child": null}', pickled)
def roundtrip(self, ob): encoded = jsonstruct.encode(ob) decoded = jsonstruct.decode(encoded) self.assertEqual(decoded, ob) return decoded