2012-11-23 04:12:33 +04:00
|
|
|
from rest_framework.compat import BytesIO
|
2012-11-22 03:20:49 +04:00
|
|
|
|
2012-11-15 02:04:46 +04:00
|
|
|
import datetime
|
2012-11-25 02:19:03 +04:00
|
|
|
import six
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2012-11-15 02:04:46 +04:00
|
|
|
from django.test import TestCase
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2012-11-15 02:04:46 +04:00
|
|
|
from rest_framework import serializers
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
|
2012-11-15 02:04:46 +04:00
|
|
|
class UploadedFile(object):
|
|
|
|
def __init__(self, file, created=None):
|
|
|
|
self.file = file
|
|
|
|
self.created = created or datetime.datetime.now()
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
|
2012-11-15 02:04:46 +04:00
|
|
|
class UploadedFileSerializer(serializers.Serializer):
|
|
|
|
file = serializers.FileField()
|
|
|
|
created = serializers.DateTimeField()
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2012-11-15 02:04:46 +04:00
|
|
|
def restore_object(self, attrs, instance=None):
|
|
|
|
if instance:
|
|
|
|
instance.file = attrs['file']
|
|
|
|
instance.created = attrs['created']
|
|
|
|
return instance
|
|
|
|
return UploadedFile(**attrs)
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
|
2012-11-15 02:04:46 +04:00
|
|
|
class FileSerializerTests(TestCase):
|
|
|
|
|
|
|
|
def test_create(self):
|
|
|
|
now = datetime.datetime.now()
|
2012-11-25 02:19:03 +04:00
|
|
|
file = BytesIO(six.b('stuff'))
|
2012-11-15 02:04:46 +04:00
|
|
|
file.name = 'stuff.txt'
|
2012-11-23 04:12:33 +04:00
|
|
|
file.size = len(file.getvalue())
|
2012-11-15 02:04:46 +04:00
|
|
|
serializer = UploadedFileSerializer(data={'created': now}, files={'file': file})
|
|
|
|
uploaded_file = UploadedFile(file=file, created=now)
|
|
|
|
self.assertTrue(serializer.is_valid())
|
|
|
|
self.assertEquals(serializer.object.created, uploaded_file.created)
|
|
|
|
self.assertEquals(serializer.object.file, uploaded_file.file)
|
|
|
|
self.assertFalse(serializer.object is uploaded_file)
|