def test_unicode_mixin(self): obj = UnicodeMixin('test') self.assertEqual(type(obj), UnicodeMixin) self.assertEqual(str(obj), u('test')) # Encode into JSON content = jsonpickle.encode(obj) # Resurrect from JSON new_obj = jsonpickle.decode(content) new_obj += ' passed' self.assertEqual(str(new_obj), u('test passed')) self.assertEqual(type(new_obj), UnicodeMixin) self.assertTrue(new_obj.ok())
def _flatten_key_value_pair(self, k, v, data): """Flatten a key/value pair into the passed-in dictionary.""" if not util.is_picklable(k, v): return data if not isinstance(k, str): try: k = repr(k) except: k = str(k) data[k] = self.flatten(v) return data
def _flatten_obj_instance(self, obj): """Recursively flatten an instance and return a json-friendly dict """ data = {} has_class = hasattr(obj, '__class__') has_dict = hasattr(obj, '__dict__') has_slots = not has_dict and hasattr(obj, '__slots__') has_getstate = has_dict and hasattr(obj, '__getstate__') has_getstate_support = has_getstate and hasattr(obj, '__setstate__') HandlerClass = handlers.BaseHandler._registry.get(type(obj)) if has_class and not util.is_module(obj): module, name = _getclassdetail(obj) if self.unpicklable: data[tags.OBJECT] = '%s.%s' % (module, name) # Check for a custom handler if HandlerClass: handler = HandlerClass(self) flat_obj = handler.flatten(obj, data) self._mkref(flat_obj) return flat_obj if util.is_module(obj): if self.unpicklable: data[tags.REPR] = '%s/%s' % (obj.__name__, obj.__name__) else: data = str(obj) return data if util.is_dictionary_subclass(obj): return self._flatten_dict_obj(obj, data) if has_dict: # Support objects that subclasses list and set if util.is_collection_subclass(obj): return self._flatten_collection_obj(obj, data) # Support objects with __getstate__(); this ensures that # both __setstate__() and __getstate__() are implemented if has_getstate_support: state = self.flatten(obj.__getstate__()) if self.unpicklable: data[tags.STATE] = state else: data = state return data # hack for zope persistent objects; this unghostifies the object getattr(obj, '_', None) return self._flatten_dict_obj(obj.__dict__, data) if util.is_collection_subclass(obj): return self._flatten_collection_obj(obj, data) if util.is_noncomplex(obj): return [self.flatten(v) for v in obj] if has_slots: return self._flatten_newstyle_with_slots(obj, data)