# Path: dockit/core/serializers/python.py
# class Serializer(base.Serializer):
#     """
#     Serializes a QuerySet to basic Python objects.
#     """
# 
#     internal_use_only = True
# 
#     def start_serialization(self):
#         self._current = None
#         self.objects = []
# 
#     def end_serialization(self):
#         pass
# 
#     def start_object(self, obj):
#         self._current = obj.to_portable_primitive(obj)
#         pk_field = obj._meta.get_id_field_name()
#         if pk_field in self._current:
#             del self._current[pk_field]
#         self._current.pop('@natural_key', None)
#         self._current.pop('@natural_key_hash', None)
# 
#     def end_object(self, obj):
#         entry = {
#             "collection"  : smart_unicode(obj._meta.collection),
#             "pk"     : smart_unicode(obj._get_pk_val(), strings_only=True),
#             "natural_key": obj.natural_key,
#             "natural_key_hash": obj.natural_key_hash,
#             "fields" : self._current,
#         }
#         self.objects.append(entry)
#         self._current = None
# 
#     def getvalue(self):
#         return self.objects
# 
# def Deserializer(object_list, **options):
#     """
#     Deserialize simple Python objects back into Django ORM instances.
# 
#     It's expected that you pass the Python objects themselves (instead of a
#     stream or a string) to the constructor
#     """
#     #models.get_apps()
#     use_natural_keys = options.get('use_natural_keys', True)
#     for d in object_list:
#         # Look up the model and starting build a dict of data for it.
#         doc_cls = get_base_document(d["collection"])
#         data = d['fields']
#         if use_natural_keys and 'natural_key' in d:
#             data['@natural_key'] = d['natural_key']
#         elif 'pk' in d:
#             data[doc_cls._meta.pk.attname] = doc_cls._meta.pk.to_python(d["pk"])
#         
#         if 'natural_key' in d:
#             yield base.DeserializedObject(doc_cls.to_python(data), natural_key=d['natural_key'])
#         else:
#             yield base.DeserializedObject(doc_cls.to_python(data))
# 
# Path: dockit/tests/serializers/common.py
# class ParentDocument(schema.Document):
#     title = schema.CharField()
#     subdocument = schema.ReferenceField(ChildDocument)
#     subschema = schema.SchemaField(ChildSchema)
# 
# class ChildDocument(schema.Document):
#     charfield = schema.CharField()
#     
#     def create_natural_key(self):
#         return {'charfield': self.charfield}
# 
# class ChildSchema(schema.Schema):
#     ct = schema.ModelReferenceField(ContentType)


from dockit.core.serializers.python import Serializer, Deserializer
from django.utils import unittest
from django.contrib.contenttypes.models import ContentType
from dockit.tests.serializers.common import ParentDocument, ChildDocument, ChildSchema




class PythonSerializerTestCase(unittest.TestCase):
    def setUp(self):
        self.serializer = Serializer()
        #self.deserializer = Deserializer()

    def test_serialize(self):
        child = ChildDocument(charfield='bar')
        child.save()
        parent = ParentDocument(title='foo', subdocument=child, subschema=ChildSchema(ct=ContentType.objects.all()[0]))
        assert parent.natural_key
        assert '@natural_key' in parent._primitive_data
        data = parent.to_portable_primitive(parent)
        self.assertTrue(isinstance(data['subschema']['ct'], tuple), str(data))
        self.assertTrue(isinstance(data['subdocument'], dict), "Did not give a natural key: %s" % data['subdocument'])
        self.assertTrue('@natural_key' in data, str(data))
        result = self.serializer.serialize([child, parent])
        self.assertEqual(len(result), 2)
        entry = result[1]
        self.assertTrue('fields' in entry)
        self.assertEqual(len(entry['fields']), 3, str(entry))
        del data['@natural_key']
        del data['@natural_key_hash']
        self.assertEqual(entry['fields'], data)

    def test_deserialize(self):
        payload = [{'natural_key': {'charfield': 'bar'}, 'collection': ChildDocument._meta.collection, 'fields': {'charfield': u'bar'}},

# Path: dockit/core/serializers/python.py
# class Serializer(base.Serializer):
#     """
#     Serializes a QuerySet to basic Python objects.
#     """
# 
#     internal_use_only = True
# 
#     def start_serialization(self):
#         self._current = None
#         self.objects = []
# 
#     def end_serialization(self):
#         pass
# 
#     def start_object(self, obj):
#         self._current = obj.to_portable_primitive(obj)
#         pk_field = obj._meta.get_id_field_name()
#         if pk_field in self._current:
#             del self._current[pk_field]
#         self._current.pop('@natural_key', None)
#         self._current.pop('@natural_key_hash', None)
# 
#     def end_object(self, obj):
#         entry = {
#             "collection"  : smart_unicode(obj._meta.collection),
#             "pk"     : smart_unicode(obj._get_pk_val(), strings_only=True),
#             "natural_key": obj.natural_key,
#             "natural_key_hash": obj.natural_key_hash,
#             "fields" : self._current,
#         }
#         self.objects.append(entry)
#         self._current = None
# 
#     def getvalue(self):
#         return self.objects
# 
# def Deserializer(object_list, **options):
#     """
#     Deserialize simple Python objects back into Django ORM instances.
# 
#     It's expected that you pass the Python objects themselves (instead of a
#     stream or a string) to the constructor
#     """
#     #models.get_apps()
#     use_natural_keys = options.get('use_natural_keys', True)
#     for d in object_list:
#         # Look up the model and starting build a dict of data for it.
#         doc_cls = get_base_document(d["collection"])
#         data = d['fields']
#         if use_natural_keys and 'natural_key' in d:
#             data['@natural_key'] = d['natural_key']
#         elif 'pk' in d:
#             data[doc_cls._meta.pk.attname] = doc_cls._meta.pk.to_python(d["pk"])
#         
#         if 'natural_key' in d:
#             yield base.DeserializedObject(doc_cls.to_python(data), natural_key=d['natural_key'])
#         else:
#             yield base.DeserializedObject(doc_cls.to_python(data))
# 
# Path: dockit/tests/serializers/common.py
# class ParentDocument(schema.Document):
#     title = schema.CharField()
#     subdocument = schema.ReferenceField(ChildDocument)
#     subschema = schema.SchemaField(ChildSchema)
# 
# class ChildDocument(schema.Document):
#     charfield = schema.CharField()
#     
#     def create_natural_key(self):
#         return {'charfield': self.charfield}
# 
# class ChildSchema(schema.Schema):
#     ct = schema.ModelReferenceField(ContentType)


# Path: dockit/tests/serializers/python_tests.py
from dockit.core.serializers.python import Serializer, Deserializer
from django.utils import unittest
from django.contrib.contenttypes.models import ContentType
from dockit.tests.serializers.common import ParentDocument, ChildDocument, ChildSchema





class PythonSerializerTestCase(unittest.TestCase):
    def setUp(self):
        self.serializer = Serializer()
        #self.deserializer = Deserializer()

    def test_serialize(self):
        child = ChildDocument(charfield='bar')
        child.save()
        parent = ParentDocument(title='foo', subdocument=child, subschema=ChildSchema(ct=ContentType.objects.all()[0]))
        assert parent.natural_key
        assert '@natural_key' in parent._primitive_data
        data = parent.to_portable_primitive(parent)
        self.assertTrue(isinstance(data['subschema']['ct'], tuple), str(data))
        self.assertTrue(isinstance(data['subdocument'], dict), "Did not give a natural key: %s" % data['subdocument'])
        self.assertTrue('@natural_key' in data, str(data))
        result = self.serializer.serialize([child, parent])
        self.assertEqual(len(result), 2)
        entry = result[1]
        self.assertTrue('fields' in entry)
        self.assertEqual(len(entry['fields']), 3, str(entry))
        del data['@natural_key']
        del data['@natural_key_hash']
        self.assertEqual(entry['fields'], data)

    def test_deserialize(self):
        payload = [{'natural_key': {'charfield': 'bar'}, 'collection': ChildDocument._meta.collection, 'fields': {'charfield': u'bar'}},

                   {'natural_key': {'uuid': 'DEADBEEF'}, 'collection': ParentDocument._meta.collection, 'fields': {'subdocument': {'charfield': 'bar'}, 'title': u'foo'}}]