mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-22 17:47:04 +03:00
Drop defunct tests
This commit is contained in:
parent
d84582fe1f
commit
c8764de788
|
@ -1,92 +0,0 @@
|
|||
# from __future__ import unicode_literals
|
||||
# from django.test import TestCase
|
||||
# from django.utils import six
|
||||
# from rest_framework import serializers
|
||||
# from rest_framework.compat import BytesIO
|
||||
# import datetime
|
||||
|
||||
|
||||
# class UploadedFile(object):
|
||||
# def __init__(self, file=None, created=None):
|
||||
# self.file = file
|
||||
# self.created = created or datetime.datetime.now()
|
||||
|
||||
|
||||
# class UploadedFileSerializer(serializers.Serializer):
|
||||
# file = serializers.FileField(required=False)
|
||||
# created = serializers.DateTimeField()
|
||||
|
||||
# def restore_object(self, attrs, instance=None):
|
||||
# if instance:
|
||||
# instance.file = attrs['file']
|
||||
# instance.created = attrs['created']
|
||||
# return instance
|
||||
# return UploadedFile(**attrs)
|
||||
|
||||
|
||||
# class FileSerializerTests(TestCase):
|
||||
# def test_create(self):
|
||||
# now = datetime.datetime.now()
|
||||
# file = BytesIO(six.b('stuff'))
|
||||
# file.name = 'stuff.txt'
|
||||
# file.size = len(file.getvalue())
|
||||
# serializer = UploadedFileSerializer(data={'created': now}, files={'file': file})
|
||||
# uploaded_file = UploadedFile(file=file, created=now)
|
||||
# self.assertTrue(serializer.is_valid())
|
||||
# self.assertEqual(serializer.object.created, uploaded_file.created)
|
||||
# self.assertEqual(serializer.object.file, uploaded_file.file)
|
||||
# self.assertFalse(serializer.object is uploaded_file)
|
||||
|
||||
# def test_creation_failure(self):
|
||||
# """
|
||||
# Passing files=None should result in an ValidationError
|
||||
|
||||
# Regression test for:
|
||||
# https://github.com/tomchristie/django-rest-framework/issues/542
|
||||
# """
|
||||
# now = datetime.datetime.now()
|
||||
|
||||
# serializer = UploadedFileSerializer(data={'created': now})
|
||||
# self.assertTrue(serializer.is_valid())
|
||||
# self.assertEqual(serializer.object.created, now)
|
||||
# self.assertIsNone(serializer.object.file)
|
||||
|
||||
# def test_remove_with_empty_string(self):
|
||||
# """
|
||||
# Passing empty string as data should cause file to be removed
|
||||
|
||||
# Test for:
|
||||
# https://github.com/tomchristie/django-rest-framework/issues/937
|
||||
# """
|
||||
# now = datetime.datetime.now()
|
||||
# file = BytesIO(six.b('stuff'))
|
||||
# file.name = 'stuff.txt'
|
||||
# file.size = len(file.getvalue())
|
||||
|
||||
# uploaded_file = UploadedFile(file=file, created=now)
|
||||
|
||||
# serializer = UploadedFileSerializer(instance=uploaded_file, data={'created': now, 'file': ''})
|
||||
# self.assertTrue(serializer.is_valid())
|
||||
# self.assertEqual(serializer.object.created, uploaded_file.created)
|
||||
# self.assertIsNone(serializer.object.file)
|
||||
|
||||
# def test_validation_error_with_non_file(self):
|
||||
# """
|
||||
# Passing non-files should raise a validation error.
|
||||
# """
|
||||
# now = datetime.datetime.now()
|
||||
# errmsg = 'No file was submitted. Check the encoding type on the form.'
|
||||
|
||||
# serializer = UploadedFileSerializer(data={'created': now, 'file': 'abc'})
|
||||
# self.assertFalse(serializer.is_valid())
|
||||
# self.assertEqual(serializer.errors, {'file': [errmsg]})
|
||||
|
||||
# def test_validation_with_no_data(self):
|
||||
# """
|
||||
# Validation should still function when no data dictionary is provided.
|
||||
# """
|
||||
# uploaded_file = BytesIO(six.b('stuff'))
|
||||
# uploaded_file.name = 'stuff.txt'
|
||||
# uploaded_file.size = len(uploaded_file.getvalue())
|
||||
# serializer = UploadedFileSerializer(files={'file': uploaded_file})
|
||||
# self.assertFalse(serializer.is_valid())
|
|
@ -1,406 +0,0 @@
|
|||
# from __future__ import unicode_literals
|
||||
# import json
|
||||
# from django.test import TestCase
|
||||
# from rest_framework import generics, status, serializers
|
||||
# from django.conf.urls import patterns, url
|
||||
# from rest_framework.settings import api_settings
|
||||
# from rest_framework.test import APIRequestFactory
|
||||
# from tests.models import (
|
||||
# Anchor, BasicModel, ManyToManyModel, BlogPost, BlogPostComment,
|
||||
# Album, Photo, OptionalRelationModel
|
||||
# )
|
||||
|
||||
# factory = APIRequestFactory()
|
||||
|
||||
|
||||
# class BlogPostCommentSerializer(serializers.ModelSerializer):
|
||||
# url = serializers.HyperlinkedIdentityField(view_name='blogpostcomment-detail')
|
||||
# text = serializers.CharField()
|
||||
# blog_post_url = serializers.HyperlinkedRelatedField(source='blog_post', view_name='blogpost-detail')
|
||||
|
||||
# class Meta:
|
||||
# model = BlogPostComment
|
||||
# fields = ('text', 'blog_post_url', 'url')
|
||||
|
||||
|
||||
# class PhotoSerializer(serializers.Serializer):
|
||||
# description = serializers.CharField()
|
||||
# album_url = serializers.HyperlinkedRelatedField(source='album', view_name='album-detail', queryset=Album.objects.all(), lookup_field='title')
|
||||
|
||||
# def restore_object(self, attrs, instance=None):
|
||||
# return Photo(**attrs)
|
||||
|
||||
|
||||
# class AlbumSerializer(serializers.ModelSerializer):
|
||||
# url = serializers.HyperlinkedIdentityField(view_name='album-detail', lookup_field='title')
|
||||
|
||||
# class Meta:
|
||||
# model = Album
|
||||
# fields = ('title', 'url')
|
||||
|
||||
|
||||
# class BasicSerializer(serializers.HyperlinkedModelSerializer):
|
||||
# class Meta:
|
||||
# model = BasicModel
|
||||
|
||||
|
||||
# class AnchorSerializer(serializers.HyperlinkedModelSerializer):
|
||||
# class Meta:
|
||||
# model = Anchor
|
||||
|
||||
|
||||
# class ManyToManySerializer(serializers.HyperlinkedModelSerializer):
|
||||
# class Meta:
|
||||
# model = ManyToManyModel
|
||||
|
||||
|
||||
# class BlogPostSerializer(serializers.ModelSerializer):
|
||||
# class Meta:
|
||||
# model = BlogPost
|
||||
|
||||
|
||||
# class OptionalRelationSerializer(serializers.HyperlinkedModelSerializer):
|
||||
# class Meta:
|
||||
# model = OptionalRelationModel
|
||||
|
||||
|
||||
# class BasicList(generics.ListCreateAPIView):
|
||||
# queryset = BasicModel.objects.all()
|
||||
# serializer_class = BasicSerializer
|
||||
|
||||
|
||||
# class BasicDetail(generics.RetrieveUpdateDestroyAPIView):
|
||||
# queryset = BasicModel.objects.all()
|
||||
# serializer_class = BasicSerializer
|
||||
|
||||
|
||||
# class AnchorDetail(generics.RetrieveAPIView):
|
||||
# queryset = Anchor.objects.all()
|
||||
# serializer_class = AnchorSerializer
|
||||
|
||||
|
||||
# class ManyToManyList(generics.ListAPIView):
|
||||
# queryset = ManyToManyModel.objects.all()
|
||||
# serializer_class = ManyToManySerializer
|
||||
|
||||
|
||||
# class ManyToManyDetail(generics.RetrieveAPIView):
|
||||
# queryset = ManyToManyModel.objects.all()
|
||||
# serializer_class = ManyToManySerializer
|
||||
|
||||
|
||||
# class BlogPostCommentListCreate(generics.ListCreateAPIView):
|
||||
# queryset = BlogPostComment.objects.all()
|
||||
# serializer_class = BlogPostCommentSerializer
|
||||
|
||||
|
||||
# class BlogPostCommentDetail(generics.RetrieveAPIView):
|
||||
# queryset = BlogPostComment.objects.all()
|
||||
# serializer_class = BlogPostCommentSerializer
|
||||
|
||||
|
||||
# class BlogPostDetail(generics.RetrieveAPIView):
|
||||
# queryset = BlogPost.objects.all()
|
||||
# serializer_class = BlogPostSerializer
|
||||
|
||||
|
||||
# class PhotoListCreate(generics.ListCreateAPIView):
|
||||
# queryset = Photo.objects.all()
|
||||
# serializer_class = PhotoSerializer
|
||||
|
||||
|
||||
# class AlbumDetail(generics.RetrieveAPIView):
|
||||
# queryset = Album.objects.all()
|
||||
# serializer_class = AlbumSerializer
|
||||
# lookup_field = 'title'
|
||||
|
||||
|
||||
# class OptionalRelationDetail(generics.RetrieveUpdateDestroyAPIView):
|
||||
# queryset = OptionalRelationModel.objects.all()
|
||||
# serializer_class = OptionalRelationSerializer
|
||||
|
||||
|
||||
# urlpatterns = patterns(
|
||||
# '',
|
||||
# url(r'^basic/$', BasicList.as_view(), name='basicmodel-list'),
|
||||
# url(r'^basic/(?P<pk>\d+)/$', BasicDetail.as_view(), name='basicmodel-detail'),
|
||||
# url(r'^anchor/(?P<pk>\d+)/$', AnchorDetail.as_view(), name='anchor-detail'),
|
||||
# url(r'^manytomany/$', ManyToManyList.as_view(), name='manytomanymodel-list'),
|
||||
# url(r'^manytomany/(?P<pk>\d+)/$', ManyToManyDetail.as_view(), name='manytomanymodel-detail'),
|
||||
# url(r'^posts/(?P<pk>\d+)/$', BlogPostDetail.as_view(), name='blogpost-detail'),
|
||||
# url(r'^comments/$', BlogPostCommentListCreate.as_view(), name='blogpostcomment-list'),
|
||||
# url(r'^comments/(?P<pk>\d+)/$', BlogPostCommentDetail.as_view(), name='blogpostcomment-detail'),
|
||||
# url(r'^albums/(?P<title>\w[\w-]*)/$', AlbumDetail.as_view(), name='album-detail'),
|
||||
# url(r'^photos/$', PhotoListCreate.as_view(), name='photo-list'),
|
||||
# url(r'^optionalrelation/(?P<pk>\d+)/$', OptionalRelationDetail.as_view(), name='optionalrelationmodel-detail'),
|
||||
# )
|
||||
|
||||
|
||||
# class TestBasicHyperlinkedView(TestCase):
|
||||
# urls = 'tests.test_hyperlinkedserializers'
|
||||
|
||||
# def setUp(self):
|
||||
# """
|
||||
# Create 3 BasicModel instances.
|
||||
# """
|
||||
# items = ['foo', 'bar', 'baz']
|
||||
# for item in items:
|
||||
# BasicModel(text=item).save()
|
||||
# self.objects = BasicModel.objects
|
||||
# self.data = [
|
||||
# {'url': 'http://testserver/basic/%d/' % obj.id, 'text': obj.text}
|
||||
# for obj in self.objects.all()
|
||||
# ]
|
||||
# self.list_view = BasicList.as_view()
|
||||
# self.detail_view = BasicDetail.as_view()
|
||||
|
||||
# def test_get_list_view(self):
|
||||
# """
|
||||
# GET requests to ListCreateAPIView should return list of objects.
|
||||
# """
|
||||
# request = factory.get('/basic/')
|
||||
# response = self.list_view(request).render()
|
||||
# self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
# self.assertEqual(response.data, self.data)
|
||||
|
||||
# def test_get_detail_view(self):
|
||||
# """
|
||||
# GET requests to ListCreateAPIView should return list of objects.
|
||||
# """
|
||||
# request = factory.get('/basic/1')
|
||||
# response = self.detail_view(request, pk=1).render()
|
||||
# self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
# self.assertEqual(response.data, self.data[0])
|
||||
|
||||
|
||||
# class TestManyToManyHyperlinkedView(TestCase):
|
||||
# urls = 'tests.test_hyperlinkedserializers'
|
||||
|
||||
# def setUp(self):
|
||||
# """
|
||||
# Create 3 BasicModel instances.
|
||||
# """
|
||||
# items = ['foo', 'bar', 'baz']
|
||||
# anchors = []
|
||||
# for item in items:
|
||||
# anchor = Anchor(text=item)
|
||||
# anchor.save()
|
||||
# anchors.append(anchor)
|
||||
|
||||
# manytomany = ManyToManyModel()
|
||||
# manytomany.save()
|
||||
# manytomany.rel.add(*anchors)
|
||||
|
||||
# self.data = [{
|
||||
# 'url': 'http://testserver/manytomany/1/',
|
||||
# 'rel': [
|
||||
# 'http://testserver/anchor/1/',
|
||||
# 'http://testserver/anchor/2/',
|
||||
# 'http://testserver/anchor/3/',
|
||||
# ]
|
||||
# }]
|
||||
# self.list_view = ManyToManyList.as_view()
|
||||
# self.detail_view = ManyToManyDetail.as_view()
|
||||
|
||||
# def test_get_list_view(self):
|
||||
# """
|
||||
# GET requests to ListCreateAPIView should return list of objects.
|
||||
# """
|
||||
# request = factory.get('/manytomany/')
|
||||
# response = self.list_view(request)
|
||||
# self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
# self.assertEqual(response.data, self.data)
|
||||
|
||||
# def test_get_detail_view(self):
|
||||
# """
|
||||
# GET requests to ListCreateAPIView should return list of objects.
|
||||
# """
|
||||
# request = factory.get('/manytomany/1/')
|
||||
# response = self.detail_view(request, pk=1)
|
||||
# self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
# self.assertEqual(response.data, self.data[0])
|
||||
|
||||
|
||||
# class TestHyperlinkedIdentityFieldLookup(TestCase):
|
||||
# urls = 'tests.test_hyperlinkedserializers'
|
||||
|
||||
# def setUp(self):
|
||||
# """
|
||||
# Create 3 Album instances.
|
||||
# """
|
||||
# titles = ['foo', 'bar', 'baz']
|
||||
# for title in titles:
|
||||
# album = Album(title=title)
|
||||
# album.save()
|
||||
# self.detail_view = AlbumDetail.as_view()
|
||||
# self.data = {
|
||||
# 'foo': {'title': 'foo', 'url': 'http://testserver/albums/foo/'},
|
||||
# 'bar': {'title': 'bar', 'url': 'http://testserver/albums/bar/'},
|
||||
# 'baz': {'title': 'baz', 'url': 'http://testserver/albums/baz/'}
|
||||
# }
|
||||
|
||||
# def test_lookup_field(self):
|
||||
# """
|
||||
# GET requests to AlbumDetail view should return serialized Albums
|
||||
# with a url field keyed by `title`.
|
||||
# """
|
||||
# for album in Album.objects.all():
|
||||
# request = factory.get('/albums/{0}/'.format(album.title))
|
||||
# response = self.detail_view(request, title=album.title)
|
||||
# self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
# self.assertEqual(response.data, self.data[album.title])
|
||||
|
||||
|
||||
# class TestCreateWithForeignKeys(TestCase):
|
||||
# urls = 'tests.test_hyperlinkedserializers'
|
||||
|
||||
# def setUp(self):
|
||||
# """
|
||||
# Create a blog post
|
||||
# """
|
||||
# self.post = BlogPost.objects.create(title="Test post")
|
||||
# self.create_view = BlogPostCommentListCreate.as_view()
|
||||
|
||||
# def test_create_comment(self):
|
||||
|
||||
# data = {
|
||||
# 'text': 'A test comment',
|
||||
# 'blog_post_url': 'http://testserver/posts/1/'
|
||||
# }
|
||||
|
||||
# request = factory.post('/comments/', data=data)
|
||||
# response = self.create_view(request)
|
||||
# self.assertEqual(response.status_code, status.HTTP_201_CREATED)
|
||||
# self.assertEqual(response['Location'], 'http://testserver/comments/1/')
|
||||
# self.assertEqual(self.post.blogpostcomment_set.count(), 1)
|
||||
# self.assertEqual(self.post.blogpostcomment_set.all()[0].text, 'A test comment')
|
||||
|
||||
|
||||
# class TestCreateWithForeignKeysAndCustomSlug(TestCase):
|
||||
# urls = 'tests.test_hyperlinkedserializers'
|
||||
|
||||
# def setUp(self):
|
||||
# """
|
||||
# Create an Album
|
||||
# """
|
||||
# self.post = Album.objects.create(title='test-album')
|
||||
# self.list_create_view = PhotoListCreate.as_view()
|
||||
|
||||
# def test_create_photo(self):
|
||||
|
||||
# data = {
|
||||
# 'description': 'A test photo',
|
||||
# 'album_url': 'http://testserver/albums/test-album/'
|
||||
# }
|
||||
|
||||
# request = factory.post('/photos/', data=data)
|
||||
# response = self.list_create_view(request)
|
||||
# self.assertEqual(response.status_code, status.HTTP_201_CREATED)
|
||||
# self.assertNotIn('Location', response, msg='Location should only be included if there is a "url" field on the serializer')
|
||||
# self.assertEqual(self.post.photo_set.count(), 1)
|
||||
# self.assertEqual(self.post.photo_set.all()[0].description, 'A test photo')
|
||||
|
||||
|
||||
# class TestOptionalRelationHyperlinkedView(TestCase):
|
||||
# urls = 'tests.test_hyperlinkedserializers'
|
||||
|
||||
# def setUp(self):
|
||||
# """
|
||||
# Create 1 OptionalRelationModel instances.
|
||||
# """
|
||||
# OptionalRelationModel().save()
|
||||
# self.objects = OptionalRelationModel.objects
|
||||
# self.detail_view = OptionalRelationDetail.as_view()
|
||||
# self.data = {"url": "http://testserver/optionalrelation/1/", "other": None}
|
||||
|
||||
# def test_get_detail_view(self):
|
||||
# """
|
||||
# GET requests to RetrieveAPIView with optional relations should return None
|
||||
# for non existing relations.
|
||||
# """
|
||||
# request = factory.get('/optionalrelationmodel-detail/1')
|
||||
# response = self.detail_view(request, pk=1)
|
||||
# self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
# self.assertEqual(response.data, self.data)
|
||||
|
||||
# def test_put_detail_view(self):
|
||||
# """
|
||||
# PUT requests to RetrieveUpdateDestroyAPIView with optional relations
|
||||
# should accept None for non existing relations.
|
||||
# """
|
||||
# response = self.client.put('/optionalrelation/1/',
|
||||
# data=json.dumps(self.data),
|
||||
# content_type='application/json')
|
||||
# self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
|
||||
|
||||
# class TestOverriddenURLField(TestCase):
|
||||
# def setUp(self):
|
||||
# class OverriddenURLSerializer(serializers.HyperlinkedModelSerializer):
|
||||
# url = serializers.SerializerMethodField('get_url')
|
||||
|
||||
# class Meta:
|
||||
# model = BlogPost
|
||||
# fields = ('title', 'url')
|
||||
|
||||
# def get_url(self, obj):
|
||||
# return 'foo bar'
|
||||
|
||||
# self.Serializer = OverriddenURLSerializer
|
||||
# self.obj = BlogPost.objects.create(title='New blog post')
|
||||
|
||||
# def test_overridden_url_field(self):
|
||||
# """
|
||||
# The 'url' field should respect overriding.
|
||||
# Regression test for #936.
|
||||
# """
|
||||
# serializer = self.Serializer(self.obj)
|
||||
# self.assertEqual(
|
||||
# serializer.data,
|
||||
# {'title': 'New blog post', 'url': 'foo bar'}
|
||||
# )
|
||||
|
||||
|
||||
# class TestURLFieldNameBySettings(TestCase):
|
||||
# urls = 'tests.test_hyperlinkedserializers'
|
||||
|
||||
# def setUp(self):
|
||||
# self.saved_url_field_name = api_settings.URL_FIELD_NAME
|
||||
# api_settings.URL_FIELD_NAME = 'global_url_field'
|
||||
|
||||
# class Serializer(serializers.HyperlinkedModelSerializer):
|
||||
|
||||
# class Meta:
|
||||
# model = BlogPost
|
||||
# fields = ('title', api_settings.URL_FIELD_NAME)
|
||||
|
||||
# self.Serializer = Serializer
|
||||
# self.obj = BlogPost.objects.create(title="New blog post")
|
||||
|
||||
# def tearDown(self):
|
||||
# api_settings.URL_FIELD_NAME = self.saved_url_field_name
|
||||
|
||||
# def test_overridden_url_field_name(self):
|
||||
# request = factory.get('/posts/')
|
||||
# serializer = self.Serializer(self.obj, context={'request': request})
|
||||
# self.assertIn(api_settings.URL_FIELD_NAME, serializer.data)
|
||||
|
||||
|
||||
# class TestURLFieldNameByOptions(TestCase):
|
||||
# urls = 'tests.test_hyperlinkedserializers'
|
||||
|
||||
# def setUp(self):
|
||||
# class Serializer(serializers.HyperlinkedModelSerializer):
|
||||
|
||||
# class Meta:
|
||||
# model = BlogPost
|
||||
# fields = ('title', 'serializer_url_field')
|
||||
# url_field_name = 'serializer_url_field'
|
||||
|
||||
# self.Serializer = Serializer
|
||||
# self.obj = BlogPost.objects.create(title="New blog post")
|
||||
|
||||
# def test_overridden_url_field_name(self):
|
||||
# request = factory.get('/posts/')
|
||||
# serializer = self.Serializer(self.obj, context={'request': request})
|
||||
# self.assertIn(self.Serializer.Meta.url_field_name, serializer.data)
|
|
@ -1,39 +0,0 @@
|
|||
# from django.core.urlresolvers import reverse
|
||||
|
||||
# from django.conf.urls import patterns, url
|
||||
# from rest_framework import serializers, generics
|
||||
# from rest_framework.test import APITestCase
|
||||
# from tests.models import NullableForeignKeySource
|
||||
|
||||
|
||||
# class NullableFKSourceSerializer(serializers.ModelSerializer):
|
||||
# class Meta:
|
||||
# model = NullableForeignKeySource
|
||||
|
||||
|
||||
# class NullableFKSourceDetail(generics.RetrieveUpdateDestroyAPIView):
|
||||
# queryset = NullableForeignKeySource.objects.all()
|
||||
# serializer_class = NullableFKSourceSerializer
|
||||
|
||||
|
||||
# urlpatterns = patterns(
|
||||
# '',
|
||||
# url(r'^objects/(?P<pk>\d+)/$', NullableFKSourceDetail.as_view(), name='object-detail'),
|
||||
# )
|
||||
|
||||
|
||||
# class NullableForeignKeyTests(APITestCase):
|
||||
# """
|
||||
# DRF should be able to handle nullable foreign keys when a test
|
||||
# Client POST/PUT request is made with its own serialized object.
|
||||
# """
|
||||
# urls = 'tests.test_nullable_fields'
|
||||
|
||||
# def test_updating_object_with_null_fk(self):
|
||||
# obj = NullableForeignKeySource(name='example', target=None)
|
||||
# obj.save()
|
||||
# serialized_data = NullableFKSourceSerializer(obj).data
|
||||
|
||||
# response = self.client.put(reverse('object-detail', args=[obj.pk]), serialized_data)
|
||||
|
||||
# self.assertEqual(response.data, serialized_data)
|
|
@ -134,155 +134,3 @@ class TestSlugRelatedField(APISimpleTestCase):
|
|||
def test_representation(self):
|
||||
representation = self.field.to_representation(self.instance)
|
||||
assert representation == self.instance.name
|
||||
|
||||
# Older tests, for review...
|
||||
|
||||
# """
|
||||
# General tests for relational fields.
|
||||
# """
|
||||
# from __future__ import unicode_literals
|
||||
# from django import get_version
|
||||
# from django.db import models
|
||||
# from django.test import TestCase
|
||||
# from django.utils import unittest
|
||||
# from rest_framework import serializers
|
||||
# from tests.models import BlogPost
|
||||
|
||||
|
||||
# class NullModel(models.Model):
|
||||
# pass
|
||||
|
||||
|
||||
# class FieldTests(TestCase):
|
||||
# def test_pk_related_field_with_empty_string(self):
|
||||
# """
|
||||
# Regression test for #446
|
||||
|
||||
# https://github.com/tomchristie/django-rest-framework/issues/446
|
||||
# """
|
||||
# field = serializers.PrimaryKeyRelatedField(queryset=NullModel.objects.all())
|
||||
# self.assertRaises(serializers.ValidationError, field.to_primitive, '')
|
||||
# self.assertRaises(serializers.ValidationError, field.to_primitive, [])
|
||||
|
||||
# def test_hyperlinked_related_field_with_empty_string(self):
|
||||
# field = serializers.HyperlinkedRelatedField(queryset=NullModel.objects.all(), view_name='')
|
||||
# self.assertRaises(serializers.ValidationError, field.to_primitive, '')
|
||||
# self.assertRaises(serializers.ValidationError, field.to_primitive, [])
|
||||
|
||||
# def test_slug_related_field_with_empty_string(self):
|
||||
# field = serializers.SlugRelatedField(queryset=NullModel.objects.all(), slug_field='pk')
|
||||
# self.assertRaises(serializers.ValidationError, field.to_primitive, '')
|
||||
# self.assertRaises(serializers.ValidationError, field.to_primitive, [])
|
||||
|
||||
|
||||
# class TestManyRelatedMixin(TestCase):
|
||||
# def test_missing_many_to_many_related_field(self):
|
||||
# '''
|
||||
# Regression test for #632
|
||||
|
||||
# https://github.com/tomchristie/django-rest-framework/pull/632
|
||||
# '''
|
||||
# field = serializers.RelatedField(many=True, read_only=False)
|
||||
|
||||
# into = {}
|
||||
# field.field_from_native({}, None, 'field_name', into)
|
||||
# self.assertEqual(into['field_name'], [])
|
||||
|
||||
|
||||
# # Regression tests for #694 (`source` attribute on related fields)
|
||||
|
||||
# class RelatedFieldSourceTests(TestCase):
|
||||
# def test_related_manager_source(self):
|
||||
# """
|
||||
# Relational fields should be able to use manager-returning methods as their source.
|
||||
# """
|
||||
# BlogPost.objects.create(title='blah')
|
||||
# field = serializers.RelatedField(many=True, source='get_blogposts_manager')
|
||||
|
||||
# class ClassWithManagerMethod(object):
|
||||
# def get_blogposts_manager(self):
|
||||
# return BlogPost.objects
|
||||
|
||||
# obj = ClassWithManagerMethod()
|
||||
# value = field.field_to_native(obj, 'field_name')
|
||||
# self.assertEqual(value, ['BlogPost object'])
|
||||
|
||||
# def test_related_queryset_source(self):
|
||||
# """
|
||||
# Relational fields should be able to use queryset-returning methods as their source.
|
||||
# """
|
||||
# BlogPost.objects.create(title='blah')
|
||||
# field = serializers.RelatedField(many=True, source='get_blogposts_queryset')
|
||||
|
||||
# class ClassWithQuerysetMethod(object):
|
||||
# def get_blogposts_queryset(self):
|
||||
# return BlogPost.objects.all()
|
||||
|
||||
# obj = ClassWithQuerysetMethod()
|
||||
# value = field.field_to_native(obj, 'field_name')
|
||||
# self.assertEqual(value, ['BlogPost object'])
|
||||
|
||||
# def test_dotted_source(self):
|
||||
# """
|
||||
# Source argument should support dotted.source notation.
|
||||
# """
|
||||
# BlogPost.objects.create(title='blah')
|
||||
# field = serializers.RelatedField(many=True, source='a.b.c')
|
||||
|
||||
# class ClassWithQuerysetMethod(object):
|
||||
# a = {
|
||||
# 'b': {
|
||||
# 'c': BlogPost.objects.all()
|
||||
# }
|
||||
# }
|
||||
|
||||
# obj = ClassWithQuerysetMethod()
|
||||
# value = field.field_to_native(obj, 'field_name')
|
||||
# self.assertEqual(value, ['BlogPost object'])
|
||||
|
||||
# # Regression for #1129
|
||||
# def test_exception_for_incorect_fk(self):
|
||||
# """
|
||||
# Check that the exception message are correct if the source field
|
||||
# doesn't exist.
|
||||
# """
|
||||
# from tests.models import ManyToManySource
|
||||
|
||||
# class Meta:
|
||||
# model = ManyToManySource
|
||||
|
||||
# attrs = {
|
||||
# 'name': serializers.SlugRelatedField(
|
||||
# slug_field='name', source='banzai'),
|
||||
# 'Meta': Meta,
|
||||
# }
|
||||
|
||||
# TestSerializer = type(
|
||||
# str('TestSerializer'),
|
||||
# (serializers.ModelSerializer,),
|
||||
# attrs
|
||||
# )
|
||||
# with self.assertRaises(AttributeError):
|
||||
# TestSerializer(data={'name': 'foo'})
|
||||
|
||||
|
||||
# @unittest.skipIf(get_version() < '1.6.0', 'Upstream behaviour changed in v1.6')
|
||||
# class RelatedFieldChoicesTests(TestCase):
|
||||
# """
|
||||
# Tests for #1408 "Web browseable API doesn't have blank option on drop down list box"
|
||||
# https://github.com/tomchristie/django-rest-framework/issues/1408
|
||||
# """
|
||||
# def test_blank_option_is_added_to_choice_if_required_equals_false(self):
|
||||
# """
|
||||
|
||||
# """
|
||||
# post = BlogPost(title="Checking blank option is added")
|
||||
# post.save()
|
||||
|
||||
# queryset = BlogPost.objects.all()
|
||||
# field = serializers.RelatedField(required=False, queryset=queryset)
|
||||
|
||||
# choice_count = BlogPost.objects.count()
|
||||
# widget_count = len(field.widget.choices)
|
||||
|
||||
# self.assertEqual(widget_count, choice_count + 1, 'BLANK_CHOICE_DASH option should have been added')
|
||||
|
|
|
@ -411,30 +411,6 @@ class HyperlinkedNullableForeignKeyTests(TestCase):
|
|||
]
|
||||
self.assertEqual(serializer.data, expected)
|
||||
|
||||
# # reverse foreign keys MUST be read_only
|
||||
# # In the general case they do not provide .remove() or .clear()
|
||||
# # and cannot be arbitrarily set.
|
||||
|
||||
# def test_reverse_foreign_key_update(self):
|
||||
# data = {'id': 1, 'name': 'target-1', 'sources': [1]}
|
||||
# instance = ForeignKeyTarget.objects.get(pk=1)
|
||||
# serializer = ForeignKeyTargetSerializer(instance, data=data)
|
||||
# print serializer.is_valid()
|
||||
# print serializer.errors
|
||||
# print serializer
|
||||
# self.assertTrue(serializer.is_valid())
|
||||
# serializer.save()
|
||||
# self.assertEqual(serializer.data, data)
|
||||
|
||||
# # Ensure target 1 is updated, and everything else is as expected
|
||||
# queryset = ForeignKeyTarget.objects.all()
|
||||
# serializer = ForeignKeyTargetSerializer(queryset, many=True)
|
||||
# expected = [
|
||||
# {'id': 1, 'name': 'target-1', 'sources': [1]},
|
||||
# {'id': 2, 'name': 'target-2', 'sources': []},
|
||||
# ]
|
||||
# self.assertEqual(serializer.data, expected)
|
||||
|
||||
|
||||
class HyperlinkedNullableOneToOneTests(TestCase):
|
||||
urls = 'tests.test_relations_hyperlink'
|
||||
|
@ -455,72 +431,3 @@ class HyperlinkedNullableOneToOneTests(TestCase):
|
|||
{'url': 'http://testserver/onetoonetarget/2/', 'name': 'target-2', 'nullable_source': None},
|
||||
]
|
||||
self.assertEqual(serializer.data, expected)
|
||||
|
||||
|
||||
# # Regression tests for #694 (`source` attribute on related fields)
|
||||
|
||||
# class HyperlinkedRelatedFieldSourceTests(TestCase):
|
||||
# urls = 'tests.test_relations_hyperlink'
|
||||
|
||||
# def test_related_manager_source(self):
|
||||
# """
|
||||
# Relational fields should be able to use manager-returning methods as their source.
|
||||
# """
|
||||
# BlogPost.objects.create(title='blah')
|
||||
# field = serializers.HyperlinkedRelatedField(
|
||||
# many=True,
|
||||
# source='get_blogposts_manager',
|
||||
# view_name='dummy-url',
|
||||
# )
|
||||
# field.context = {'request': request}
|
||||
|
||||
# class ClassWithManagerMethod(object):
|
||||
# def get_blogposts_manager(self):
|
||||
# return BlogPost.objects
|
||||
|
||||
# obj = ClassWithManagerMethod()
|
||||
# value = field.field_to_native(obj, 'field_name')
|
||||
# self.assertEqual(value, ['http://testserver/dummyurl/1/'])
|
||||
|
||||
# def test_related_queryset_source(self):
|
||||
# """
|
||||
# Relational fields should be able to use queryset-returning methods as their source.
|
||||
# """
|
||||
# BlogPost.objects.create(title='blah')
|
||||
# field = serializers.HyperlinkedRelatedField(
|
||||
# many=True,
|
||||
# source='get_blogposts_queryset',
|
||||
# view_name='dummy-url',
|
||||
# )
|
||||
# field.context = {'request': request}
|
||||
|
||||
# class ClassWithQuerysetMethod(object):
|
||||
# def get_blogposts_queryset(self):
|
||||
# return BlogPost.objects.all()
|
||||
|
||||
# obj = ClassWithQuerysetMethod()
|
||||
# value = field.field_to_native(obj, 'field_name')
|
||||
# self.assertEqual(value, ['http://testserver/dummyurl/1/'])
|
||||
|
||||
# def test_dotted_source(self):
|
||||
# """
|
||||
# Source argument should support dotted.source notation.
|
||||
# """
|
||||
# BlogPost.objects.create(title='blah')
|
||||
# field = serializers.HyperlinkedRelatedField(
|
||||
# many=True,
|
||||
# source='a.b.c',
|
||||
# view_name='dummy-url',
|
||||
# )
|
||||
# field.context = {'request': request}
|
||||
|
||||
# class ClassWithQuerysetMethod(object):
|
||||
# a = {
|
||||
# 'b': {
|
||||
# 'c': BlogPost.objects.all()
|
||||
# }
|
||||
# }
|
||||
|
||||
# obj = ClassWithQuerysetMethod()
|
||||
# value = field.field_to_native(obj, 'field_name')
|
||||
# self.assertEqual(value, ['http://testserver/dummyurl/1/'])
|
||||
|
|
|
@ -1,326 +0,0 @@
|
|||
# from __future__ import unicode_literals
|
||||
# from django.db import models
|
||||
# from django.test import TestCase
|
||||
# from rest_framework import serializers
|
||||
|
||||
# from .models import OneToOneTarget
|
||||
|
||||
|
||||
# class OneToOneSource(models.Model):
|
||||
# name = models.CharField(max_length=100)
|
||||
# target = models.OneToOneField(OneToOneTarget, related_name='source',
|
||||
# null=True, blank=True)
|
||||
|
||||
|
||||
# class OneToManyTarget(models.Model):
|
||||
# name = models.CharField(max_length=100)
|
||||
|
||||
|
||||
# class OneToManySource(models.Model):
|
||||
# name = models.CharField(max_length=100)
|
||||
# target = models.ForeignKey(OneToManyTarget, related_name='sources')
|
||||
|
||||
|
||||
# class ReverseNestedOneToOneTests(TestCase):
|
||||
# def setUp(self):
|
||||
# class OneToOneSourceSerializer(serializers.ModelSerializer):
|
||||
# class Meta:
|
||||
# model = OneToOneSource
|
||||
# fields = ('id', 'name')
|
||||
|
||||
# class OneToOneTargetSerializer(serializers.ModelSerializer):
|
||||
# source = OneToOneSourceSerializer()
|
||||
|
||||
# class Meta:
|
||||
# model = OneToOneTarget
|
||||
# fields = ('id', 'name', 'source')
|
||||
|
||||
# self.Serializer = OneToOneTargetSerializer
|
||||
|
||||
# for idx in range(1, 4):
|
||||
# target = OneToOneTarget(name='target-%d' % idx)
|
||||
# target.save()
|
||||
# source = OneToOneSource(name='source-%d' % idx, target=target)
|
||||
# source.save()
|
||||
|
||||
# def test_one_to_one_retrieve(self):
|
||||
# queryset = OneToOneTarget.objects.all()
|
||||
# serializer = self.Serializer(queryset, many=True)
|
||||
# expected = [
|
||||
# {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}},
|
||||
# {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}},
|
||||
# {'id': 3, 'name': 'target-3', 'source': {'id': 3, 'name': 'source-3'}}
|
||||
# ]
|
||||
# self.assertEqual(serializer.data, expected)
|
||||
|
||||
# def test_one_to_one_create(self):
|
||||
# data = {'id': 4, 'name': 'target-4', 'source': {'id': 4, 'name': 'source-4'}}
|
||||
# serializer = self.Serializer(data=data)
|
||||
# self.assertTrue(serializer.is_valid())
|
||||
# obj = serializer.save()
|
||||
# self.assertEqual(serializer.data, data)
|
||||
# self.assertEqual(obj.name, 'target-4')
|
||||
|
||||
# # Ensure (target 4, target_source 4, source 4) are added, and
|
||||
# # everything else is as expected.
|
||||
# queryset = OneToOneTarget.objects.all()
|
||||
# serializer = self.Serializer(queryset, many=True)
|
||||
# expected = [
|
||||
# {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}},
|
||||
# {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}},
|
||||
# {'id': 3, 'name': 'target-3', 'source': {'id': 3, 'name': 'source-3'}},
|
||||
# {'id': 4, 'name': 'target-4', 'source': {'id': 4, 'name': 'source-4'}}
|
||||
# ]
|
||||
# self.assertEqual(serializer.data, expected)
|
||||
|
||||
# def test_one_to_one_create_with_invalid_data(self):
|
||||
# data = {'id': 4, 'name': 'target-4', 'source': {'id': 4}}
|
||||
# serializer = self.Serializer(data=data)
|
||||
# self.assertFalse(serializer.is_valid())
|
||||
# self.assertEqual(serializer.errors, {'source': [{'name': ['This field is required.']}]})
|
||||
|
||||
# def test_one_to_one_update(self):
|
||||
# data = {'id': 3, 'name': 'target-3-updated', 'source': {'id': 3, 'name': 'source-3-updated'}}
|
||||
# instance = OneToOneTarget.objects.get(pk=3)
|
||||
# serializer = self.Serializer(instance, data=data)
|
||||
# self.assertTrue(serializer.is_valid())
|
||||
# obj = serializer.save()
|
||||
# self.assertEqual(serializer.data, data)
|
||||
# self.assertEqual(obj.name, 'target-3-updated')
|
||||
|
||||
# # Ensure (target 3, target_source 3, source 3) are updated,
|
||||
# # and everything else is as expected.
|
||||
# queryset = OneToOneTarget.objects.all()
|
||||
# serializer = self.Serializer(queryset, many=True)
|
||||
# expected = [
|
||||
# {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}},
|
||||
# {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}},
|
||||
# {'id': 3, 'name': 'target-3-updated', 'source': {'id': 3, 'name': 'source-3-updated'}}
|
||||
# ]
|
||||
# self.assertEqual(serializer.data, expected)
|
||||
|
||||
|
||||
# class ForwardNestedOneToOneTests(TestCase):
|
||||
# def setUp(self):
|
||||
# class OneToOneTargetSerializer(serializers.ModelSerializer):
|
||||
# class Meta:
|
||||
# model = OneToOneTarget
|
||||
# fields = ('id', 'name')
|
||||
|
||||
# class OneToOneSourceSerializer(serializers.ModelSerializer):
|
||||
# target = OneToOneTargetSerializer()
|
||||
|
||||
# class Meta:
|
||||
# model = OneToOneSource
|
||||
# fields = ('id', 'name', 'target')
|
||||
|
||||
# self.Serializer = OneToOneSourceSerializer
|
||||
|
||||
# for idx in range(1, 4):
|
||||
# target = OneToOneTarget(name='target-%d' % idx)
|
||||
# target.save()
|
||||
# source = OneToOneSource(name='source-%d' % idx, target=target)
|
||||
# source.save()
|
||||
|
||||
# def test_one_to_one_retrieve(self):
|
||||
# queryset = OneToOneSource.objects.all()
|
||||
# serializer = self.Serializer(queryset, many=True)
|
||||
# expected = [
|
||||
# {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}},
|
||||
# {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}},
|
||||
# {'id': 3, 'name': 'source-3', 'target': {'id': 3, 'name': 'target-3'}}
|
||||
# ]
|
||||
# self.assertEqual(serializer.data, expected)
|
||||
|
||||
# def test_one_to_one_create(self):
|
||||
# data = {'id': 4, 'name': 'source-4', 'target': {'id': 4, 'name': 'target-4'}}
|
||||
# serializer = self.Serializer(data=data)
|
||||
# self.assertTrue(serializer.is_valid())
|
||||
# obj = serializer.save()
|
||||
# self.assertEqual(serializer.data, data)
|
||||
# self.assertEqual(obj.name, 'source-4')
|
||||
|
||||
# # Ensure (target 4, target_source 4, source 4) are added, and
|
||||
# # everything else is as expected.
|
||||
# queryset = OneToOneSource.objects.all()
|
||||
# serializer = self.Serializer(queryset, many=True)
|
||||
# expected = [
|
||||
# {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}},
|
||||
# {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}},
|
||||
# {'id': 3, 'name': 'source-3', 'target': {'id': 3, 'name': 'target-3'}},
|
||||
# {'id': 4, 'name': 'source-4', 'target': {'id': 4, 'name': 'target-4'}}
|
||||
# ]
|
||||
# self.assertEqual(serializer.data, expected)
|
||||
|
||||
# def test_one_to_one_create_with_invalid_data(self):
|
||||
# data = {'id': 4, 'name': 'source-4', 'target': {'id': 4}}
|
||||
# serializer = self.Serializer(data=data)
|
||||
# self.assertFalse(serializer.is_valid())
|
||||
# self.assertEqual(serializer.errors, {'target': [{'name': ['This field is required.']}]})
|
||||
|
||||
# def test_one_to_one_update(self):
|
||||
# data = {'id': 3, 'name': 'source-3-updated', 'target': {'id': 3, 'name': 'target-3-updated'}}
|
||||
# instance = OneToOneSource.objects.get(pk=3)
|
||||
# serializer = self.Serializer(instance, data=data)
|
||||
# self.assertTrue(serializer.is_valid())
|
||||
# obj = serializer.save()
|
||||
# self.assertEqual(serializer.data, data)
|
||||
# self.assertEqual(obj.name, 'source-3-updated')
|
||||
|
||||
# # Ensure (target 3, target_source 3, source 3) are updated,
|
||||
# # and everything else is as expected.
|
||||
# queryset = OneToOneSource.objects.all()
|
||||
# serializer = self.Serializer(queryset, many=True)
|
||||
# expected = [
|
||||
# {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}},
|
||||
# {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}},
|
||||
# {'id': 3, 'name': 'source-3-updated', 'target': {'id': 3, 'name': 'target-3-updated'}}
|
||||
# ]
|
||||
# self.assertEqual(serializer.data, expected)
|
||||
|
||||
# def test_one_to_one_update_to_null(self):
|
||||
# data = {'id': 3, 'name': 'source-3-updated', 'target': None}
|
||||
# instance = OneToOneSource.objects.get(pk=3)
|
||||
# serializer = self.Serializer(instance, data=data)
|
||||
# self.assertTrue(serializer.is_valid())
|
||||
# obj = serializer.save()
|
||||
|
||||
# self.assertEqual(serializer.data, data)
|
||||
# self.assertEqual(obj.name, 'source-3-updated')
|
||||
# self.assertEqual(obj.target, None)
|
||||
|
||||
# queryset = OneToOneSource.objects.all()
|
||||
# serializer = self.Serializer(queryset, many=True)
|
||||
# expected = [
|
||||
# {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}},
|
||||
# {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}},
|
||||
# {'id': 3, 'name': 'source-3-updated', 'target': None}
|
||||
# ]
|
||||
# self.assertEqual(serializer.data, expected)
|
||||
|
||||
# # TODO: Nullable 1-1 tests
|
||||
# # def test_one_to_one_delete(self):
|
||||
# # data = {'id': 3, 'name': 'target-3', 'target_source': None}
|
||||
# # instance = OneToOneTarget.objects.get(pk=3)
|
||||
# # serializer = self.Serializer(instance, data=data)
|
||||
# # self.assertTrue(serializer.is_valid())
|
||||
# # serializer.save()
|
||||
|
||||
# # # Ensure (target_source 3, source 3) are deleted,
|
||||
# # # and everything else is as expected.
|
||||
# # queryset = OneToOneTarget.objects.all()
|
||||
# # serializer = self.Serializer(queryset)
|
||||
# # expected = [
|
||||
# # {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}},
|
||||
# # {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}},
|
||||
# # {'id': 3, 'name': 'target-3', 'source': None}
|
||||
# # ]
|
||||
# # self.assertEqual(serializer.data, expected)
|
||||
|
||||
|
||||
# class ReverseNestedOneToManyTests(TestCase):
|
||||
# def setUp(self):
|
||||
# class OneToManySourceSerializer(serializers.ModelSerializer):
|
||||
# class Meta:
|
||||
# model = OneToManySource
|
||||
# fields = ('id', 'name')
|
||||
|
||||
# class OneToManyTargetSerializer(serializers.ModelSerializer):
|
||||
# sources = OneToManySourceSerializer(many=True, allow_add_remove=True)
|
||||
|
||||
# class Meta:
|
||||
# model = OneToManyTarget
|
||||
# fields = ('id', 'name', 'sources')
|
||||
|
||||
# self.Serializer = OneToManyTargetSerializer
|
||||
|
||||
# target = OneToManyTarget(name='target-1')
|
||||
# target.save()
|
||||
# for idx in range(1, 4):
|
||||
# source = OneToManySource(name='source-%d' % idx, target=target)
|
||||
# source.save()
|
||||
|
||||
# def test_one_to_many_retrieve(self):
|
||||
# queryset = OneToManyTarget.objects.all()
|
||||
# serializer = self.Serializer(queryset, many=True)
|
||||
# expected = [
|
||||
# {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'},
|
||||
# {'id': 2, 'name': 'source-2'},
|
||||
# {'id': 3, 'name': 'source-3'}]},
|
||||
# ]
|
||||
# self.assertEqual(serializer.data, expected)
|
||||
|
||||
# def test_one_to_many_create(self):
|
||||
# data = {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'},
|
||||
# {'id': 2, 'name': 'source-2'},
|
||||
# {'id': 3, 'name': 'source-3'},
|
||||
# {'id': 4, 'name': 'source-4'}]}
|
||||
# instance = OneToManyTarget.objects.get(pk=1)
|
||||
# serializer = self.Serializer(instance, data=data)
|
||||
# self.assertTrue(serializer.is_valid())
|
||||
# obj = serializer.save()
|
||||
# self.assertEqual(serializer.data, data)
|
||||
# self.assertEqual(obj.name, 'target-1')
|
||||
|
||||
# # Ensure source 4 is added, and everything else is as
|
||||
# # expected.
|
||||
# queryset = OneToManyTarget.objects.all()
|
||||
# serializer = self.Serializer(queryset, many=True)
|
||||
# expected = [
|
||||
# {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'},
|
||||
# {'id': 2, 'name': 'source-2'},
|
||||
# {'id': 3, 'name': 'source-3'},
|
||||
# {'id': 4, 'name': 'source-4'}]}
|
||||
# ]
|
||||
# self.assertEqual(serializer.data, expected)
|
||||
|
||||
# def test_one_to_many_create_with_invalid_data(self):
|
||||
# data = {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'},
|
||||
# {'id': 2, 'name': 'source-2'},
|
||||
# {'id': 3, 'name': 'source-3'},
|
||||
# {'id': 4}]}
|
||||
# serializer = self.Serializer(data=data)
|
||||
# self.assertFalse(serializer.is_valid())
|
||||
# self.assertEqual(serializer.errors, {'sources': [{}, {}, {}, {'name': ['This field is required.']}]})
|
||||
|
||||
# def test_one_to_many_update(self):
|
||||
# data = {'id': 1, 'name': 'target-1-updated', 'sources': [{'id': 1, 'name': 'source-1-updated'},
|
||||
# {'id': 2, 'name': 'source-2'},
|
||||
# {'id': 3, 'name': 'source-3'}]}
|
||||
# instance = OneToManyTarget.objects.get(pk=1)
|
||||
# serializer = self.Serializer(instance, data=data)
|
||||
# self.assertTrue(serializer.is_valid())
|
||||
# obj = serializer.save()
|
||||
# self.assertEqual(serializer.data, data)
|
||||
# self.assertEqual(obj.name, 'target-1-updated')
|
||||
|
||||
# # Ensure (target 1, source 1) are updated,
|
||||
# # and everything else is as expected.
|
||||
# queryset = OneToManyTarget.objects.all()
|
||||
# serializer = self.Serializer(queryset, many=True)
|
||||
# expected = [
|
||||
# {'id': 1, 'name': 'target-1-updated', 'sources': [{'id': 1, 'name': 'source-1-updated'},
|
||||
# {'id': 2, 'name': 'source-2'},
|
||||
# {'id': 3, 'name': 'source-3'}]}
|
||||
|
||||
# ]
|
||||
# self.assertEqual(serializer.data, expected)
|
||||
|
||||
# def test_one_to_many_delete(self):
|
||||
# data = {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'},
|
||||
# {'id': 3, 'name': 'source-3'}]}
|
||||
# instance = OneToManyTarget.objects.get(pk=1)
|
||||
# serializer = self.Serializer(instance, data=data)
|
||||
# self.assertTrue(serializer.is_valid())
|
||||
# serializer.save()
|
||||
|
||||
# # Ensure source 2 is deleted, and everything else is as
|
||||
# # expected.
|
||||
# queryset = OneToManyTarget.objects.all()
|
||||
# serializer = self.Serializer(queryset, many=True)
|
||||
# expected = [
|
||||
# {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'},
|
||||
# {'id': 3, 'name': 'source-3'}]}
|
||||
|
||||
# ]
|
||||
# self.assertEqual(serializer.data, expected)
|
|
@ -398,27 +398,6 @@ class PKNullableForeignKeyTests(TestCase):
|
|||
]
|
||||
self.assertEqual(serializer.data, expected)
|
||||
|
||||
# reverse foreign keys MUST be read_only
|
||||
# In the general case they do not provide .remove() or .clear()
|
||||
# and cannot be arbitrarily set.
|
||||
|
||||
# def test_reverse_foreign_key_update(self):
|
||||
# data = {'id': 1, 'name': 'target-1', 'sources': [1]}
|
||||
# instance = ForeignKeyTarget.objects.get(pk=1)
|
||||
# serializer = ForeignKeyTargetSerializer(instance, data=data)
|
||||
# self.assertTrue(serializer.is_valid())
|
||||
# self.assertEqual(serializer.data, data)
|
||||
# serializer.save()
|
||||
|
||||
# # Ensure target 1 is updated, and everything else is as expected
|
||||
# queryset = ForeignKeyTarget.objects.all()
|
||||
# serializer = ForeignKeyTargetSerializer(queryset, many=True)
|
||||
# expected = [
|
||||
# {'id': 1, 'name': 'target-1', 'sources': [1]},
|
||||
# {'id': 2, 'name': 'target-2', 'sources': []},
|
||||
# ]
|
||||
# self.assertEqual(serializer.data, expected)
|
||||
|
||||
|
||||
class PKNullableOneToOneTests(TestCase):
|
||||
def setUp(self):
|
||||
|
@ -437,113 +416,3 @@ class PKNullableOneToOneTests(TestCase):
|
|||
{'id': 2, 'name': 'target-2', 'nullable_source': 1},
|
||||
]
|
||||
self.assertEqual(serializer.data, expected)
|
||||
|
||||
|
||||
# The below models and tests ensure that serializer fields corresponding
|
||||
# to a ManyToManyField field with a user-specified ``through`` model are
|
||||
# set to read only
|
||||
|
||||
|
||||
# class ManyToManyThroughTarget(models.Model):
|
||||
# name = models.CharField(max_length=100)
|
||||
|
||||
|
||||
# class ManyToManyThrough(models.Model):
|
||||
# source = models.ForeignKey('ManyToManyThroughSource')
|
||||
# target = models.ForeignKey(ManyToManyThroughTarget)
|
||||
|
||||
|
||||
# class ManyToManyThroughSource(models.Model):
|
||||
# name = models.CharField(max_length=100)
|
||||
# targets = models.ManyToManyField(ManyToManyThroughTarget,
|
||||
# related_name='sources',
|
||||
# through='ManyToManyThrough')
|
||||
|
||||
|
||||
# class ManyToManyThroughTargetSerializer(serializers.ModelSerializer):
|
||||
# class Meta:
|
||||
# model = ManyToManyThroughTarget
|
||||
# fields = ('id', 'name', 'sources')
|
||||
|
||||
|
||||
# class ManyToManyThroughSourceSerializer(serializers.ModelSerializer):
|
||||
# class Meta:
|
||||
# model = ManyToManyThroughSource
|
||||
# fields = ('id', 'name', 'targets')
|
||||
|
||||
|
||||
# class PKManyToManyThroughTests(TestCase):
|
||||
# def setUp(self):
|
||||
# self.source = ManyToManyThroughSource.objects.create(
|
||||
# name='through-source-1')
|
||||
# self.target = ManyToManyThroughTarget.objects.create(
|
||||
# name='through-target-1')
|
||||
|
||||
# def test_many_to_many_create(self):
|
||||
# data = {'id': 2, 'name': 'source-2', 'targets': [self.target.pk]}
|
||||
# serializer = ManyToManyThroughSourceSerializer(data=data)
|
||||
# self.assertTrue(serializer.is_valid())
|
||||
# obj = serializer.save()
|
||||
# self.assertEqual(obj.name, 'source-2')
|
||||
# self.assertEqual(obj.targets.count(), 0)
|
||||
|
||||
# def test_many_to_many_reverse_create(self):
|
||||
# data = {'id': 2, 'name': 'target-2', 'sources': [self.source.pk]}
|
||||
# serializer = ManyToManyThroughTargetSerializer(data=data)
|
||||
# self.assertTrue(serializer.is_valid())
|
||||
# obj = serializer.save()
|
||||
# self.assertEqual(obj.name, 'target-2')
|
||||
# self.assertEqual(obj.sources.count(), 0)
|
||||
|
||||
|
||||
# # Regression tests for #694 (`source` attribute on related fields)
|
||||
|
||||
|
||||
# class PrimaryKeyRelatedFieldSourceTests(TestCase):
|
||||
# def test_related_manager_source(self):
|
||||
# """
|
||||
# Relational fields should be able to use manager-returning methods as their source.
|
||||
# """
|
||||
# BlogPost.objects.create(title='blah')
|
||||
# field = serializers.PrimaryKeyRelatedField(many=True, source='get_blogposts_manager')
|
||||
|
||||
# class ClassWithManagerMethod(object):
|
||||
# def get_blogposts_manager(self):
|
||||
# return BlogPost.objects
|
||||
|
||||
# obj = ClassWithManagerMethod()
|
||||
# value = field.field_to_native(obj, 'field_name')
|
||||
# self.assertEqual(value, [1])
|
||||
|
||||
# def test_related_queryset_source(self):
|
||||
# """
|
||||
# Relational fields should be able to use queryset-returning methods as their source.
|
||||
# """
|
||||
# BlogPost.objects.create(title='blah')
|
||||
# field = serializers.PrimaryKeyRelatedField(many=True, source='get_blogposts_queryset')
|
||||
|
||||
# class ClassWithQuerysetMethod(object):
|
||||
# def get_blogposts_queryset(self):
|
||||
# return BlogPost.objects.all()
|
||||
|
||||
# obj = ClassWithQuerysetMethod()
|
||||
# value = field.field_to_native(obj, 'field_name')
|
||||
# self.assertEqual(value, [1])
|
||||
|
||||
# def test_dotted_source(self):
|
||||
# """
|
||||
# Source argument should support dotted.source notation.
|
||||
# """
|
||||
# BlogPost.objects.create(title='blah')
|
||||
# field = serializers.PrimaryKeyRelatedField(many=True, source='a.b.c')
|
||||
|
||||
# class ClassWithQuerysetMethod(object):
|
||||
# a = {
|
||||
# 'b': {
|
||||
# 'c': BlogPost.objects.all()
|
||||
# }
|
||||
# }
|
||||
|
||||
# obj = ClassWithQuerysetMethod()
|
||||
# value = field.field_to_native(obj, 'field_name')
|
||||
# self.assertEqual(value, [1])
|
||||
|
|
|
@ -179,89 +179,6 @@ class TestContentParsing(TestCase):
|
|||
self.assertEqual(request._data, Empty)
|
||||
self.assertEqual(request._files, Empty)
|
||||
|
||||
# def test_accessing_post_after_data_form(self):
|
||||
# """
|
||||
# Ensures request.POST can be accessed after request.DATA in
|
||||
# form request.
|
||||
# """
|
||||
# data = {'qwerty': 'uiop'}
|
||||
# request = factory.post('/', data=data)
|
||||
# self.assertEqual(request.DATA.items(), data.items())
|
||||
# self.assertEqual(request.POST.items(), data.items())
|
||||
|
||||
# def test_accessing_post_after_data_for_json(self):
|
||||
# """
|
||||
# Ensures request.POST can be accessed after request.DATA in
|
||||
# json request.
|
||||
# """
|
||||
# data = {'qwerty': 'uiop'}
|
||||
# content = json.dumps(data)
|
||||
# content_type = 'application/json'
|
||||
# parsers = (JSONParser, )
|
||||
|
||||
# request = factory.post('/', content, content_type=content_type,
|
||||
# parsers=parsers)
|
||||
# self.assertEqual(request.DATA.items(), data.items())
|
||||
# self.assertEqual(request.POST.items(), [])
|
||||
|
||||
# def test_accessing_post_after_data_for_overloaded_json(self):
|
||||
# """
|
||||
# Ensures request.POST can be accessed after request.DATA in overloaded
|
||||
# json request.
|
||||
# """
|
||||
# data = {'qwerty': 'uiop'}
|
||||
# content = json.dumps(data)
|
||||
# content_type = 'application/json'
|
||||
# parsers = (JSONParser, )
|
||||
# form_data = {Request._CONTENT_PARAM: content,
|
||||
# Request._CONTENTTYPE_PARAM: content_type}
|
||||
|
||||
# request = factory.post('/', form_data, parsers=parsers)
|
||||
# self.assertEqual(request.DATA.items(), data.items())
|
||||
# self.assertEqual(request.POST.items(), form_data.items())
|
||||
|
||||
# def test_accessing_data_after_post_form(self):
|
||||
# """
|
||||
# Ensures request.DATA can be accessed after request.POST in
|
||||
# form request.
|
||||
# """
|
||||
# data = {'qwerty': 'uiop'}
|
||||
# parsers = (FormParser, MultiPartParser)
|
||||
# request = factory.post('/', data, parsers=parsers)
|
||||
|
||||
# self.assertEqual(request.POST.items(), data.items())
|
||||
# self.assertEqual(request.DATA.items(), data.items())
|
||||
|
||||
# def test_accessing_data_after_post_for_json(self):
|
||||
# """
|
||||
# Ensures request.DATA can be accessed after request.POST in
|
||||
# json request.
|
||||
# """
|
||||
# data = {'qwerty': 'uiop'}
|
||||
# content = json.dumps(data)
|
||||
# content_type = 'application/json'
|
||||
# parsers = (JSONParser, )
|
||||
# request = factory.post('/', content, content_type=content_type,
|
||||
# parsers=parsers)
|
||||
# self.assertEqual(request.POST.items(), [])
|
||||
# self.assertEqual(request.DATA.items(), data.items())
|
||||
|
||||
# def test_accessing_data_after_post_for_overloaded_json(self):
|
||||
# """
|
||||
# Ensures request.DATA can be accessed after request.POST in overloaded
|
||||
# json request
|
||||
# """
|
||||
# data = {'qwerty': 'uiop'}
|
||||
# content = json.dumps(data)
|
||||
# content_type = 'application/json'
|
||||
# parsers = (JSONParser, )
|
||||
# form_data = {Request._CONTENT_PARAM: content,
|
||||
# Request._CONTENTTYPE_PARAM: content_type}
|
||||
|
||||
# request = factory.post('/', form_data, parsers=parsers)
|
||||
# self.assertEqual(request.POST.items(), form_data.items())
|
||||
# self.assertEqual(request.DATA.items(), data.items())
|
||||
|
||||
|
||||
class MockView(APIView):
|
||||
authentication_classes = (SessionAuthentication,)
|
||||
|
@ -301,18 +218,6 @@ class TestContentParsingWithAuthentication(TestCase):
|
|||
response = self.csrf_client.post('/', content)
|
||||
self.assertEqual(status.HTTP_200_OK, response.status_code)
|
||||
|
||||
# def test_user_logged_in_authentication_has_post_when_logged_in(self):
|
||||
# """Ensures request.POST exists after UserLoggedInAuthentication when user does log in"""
|
||||
# self.client.login(username='john', password='password')
|
||||
# self.csrf_client.login(username='john', password='password')
|
||||
# content = {'example': 'example'}
|
||||
|
||||
# response = self.client.post('/', content)
|
||||
# self.assertEqual(status.OK, response.status_code, "POST data is malformed")
|
||||
|
||||
# response = self.csrf_client.post('/', content)
|
||||
# self.assertEqual(status.OK, response.status_code, "POST data is malformed")
|
||||
|
||||
|
||||
class TestUserSetter(TestCase):
|
||||
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -121,161 +121,3 @@ class BulkCreateSerializerTests(TestCase):
|
|||
expected_errors = {'non_field_errors': ['Expected a list of items but got type `dict`.']}
|
||||
|
||||
self.assertEqual(serializer.errors, expected_errors)
|
||||
|
||||
|
||||
# class BulkUpdateSerializerTests(TestCase):
|
||||
# """
|
||||
# Updating multiple instances using serializers.
|
||||
# """
|
||||
|
||||
# def setUp(self):
|
||||
# class Book(object):
|
||||
# """
|
||||
# A data type that can be persisted to a mock storage backend
|
||||
# with `.save()` and `.delete()`.
|
||||
# """
|
||||
# object_map = {}
|
||||
|
||||
# def __init__(self, id, title, author):
|
||||
# self.id = id
|
||||
# self.title = title
|
||||
# self.author = author
|
||||
|
||||
# def save(self):
|
||||
# Book.object_map[self.id] = self
|
||||
|
||||
# def delete(self):
|
||||
# del Book.object_map[self.id]
|
||||
|
||||
# class BookSerializer(serializers.Serializer):
|
||||
# id = serializers.IntegerField()
|
||||
# title = serializers.CharField(max_length=100)
|
||||
# author = serializers.CharField(max_length=100)
|
||||
|
||||
# def restore_object(self, attrs, instance=None):
|
||||
# if instance:
|
||||
# instance.id = attrs['id']
|
||||
# instance.title = attrs['title']
|
||||
# instance.author = attrs['author']
|
||||
# return instance
|
||||
# return Book(**attrs)
|
||||
|
||||
# self.Book = Book
|
||||
# self.BookSerializer = BookSerializer
|
||||
|
||||
# data = [
|
||||
# {
|
||||
# 'id': 0,
|
||||
# 'title': 'The electric kool-aid acid test',
|
||||
# 'author': 'Tom Wolfe'
|
||||
# }, {
|
||||
# 'id': 1,
|
||||
# 'title': 'If this is a man',
|
||||
# 'author': 'Primo Levi'
|
||||
# }, {
|
||||
# 'id': 2,
|
||||
# 'title': 'The wind-up bird chronicle',
|
||||
# 'author': 'Haruki Murakami'
|
||||
# }
|
||||
# ]
|
||||
|
||||
# for item in data:
|
||||
# book = Book(item['id'], item['title'], item['author'])
|
||||
# book.save()
|
||||
|
||||
# def books(self):
|
||||
# """
|
||||
# Return all the objects in the mock storage backend.
|
||||
# """
|
||||
# return self.Book.object_map.values()
|
||||
|
||||
# def test_bulk_update_success(self):
|
||||
# """
|
||||
# Correct bulk update serialization should return the input data.
|
||||
# """
|
||||
# data = [
|
||||
# {
|
||||
# 'id': 0,
|
||||
# 'title': 'The electric kool-aid acid test',
|
||||
# 'author': 'Tom Wolfe'
|
||||
# }, {
|
||||
# 'id': 2,
|
||||
# 'title': 'Kafka on the shore',
|
||||
# 'author': 'Haruki Murakami'
|
||||
# }
|
||||
# ]
|
||||
# serializer = self.BookSerializer(self.books(), data=data, many=True, allow_add_remove=True)
|
||||
# self.assertEqual(serializer.is_valid(), True)
|
||||
# self.assertEqual(serializer.data, data)
|
||||
# serializer.save()
|
||||
# new_data = self.BookSerializer(self.books(), many=True).data
|
||||
|
||||
# self.assertEqual(data, new_data)
|
||||
|
||||
# def test_bulk_update_and_create(self):
|
||||
# """
|
||||
# Bulk update serialization may also include created items.
|
||||
# """
|
||||
# data = [
|
||||
# {
|
||||
# 'id': 0,
|
||||
# 'title': 'The electric kool-aid acid test',
|
||||
# 'author': 'Tom Wolfe'
|
||||
# }, {
|
||||
# 'id': 3,
|
||||
# 'title': 'Kafka on the shore',
|
||||
# 'author': 'Haruki Murakami'
|
||||
# }
|
||||
# ]
|
||||
# serializer = self.BookSerializer(self.books(), data=data, many=True, allow_add_remove=True)
|
||||
# self.assertEqual(serializer.is_valid(), True)
|
||||
# self.assertEqual(serializer.data, data)
|
||||
# serializer.save()
|
||||
# new_data = self.BookSerializer(self.books(), many=True).data
|
||||
# self.assertEqual(data, new_data)
|
||||
|
||||
# def test_bulk_update_invalid_create(self):
|
||||
# """
|
||||
# Bulk update serialization without allow_add_remove may not create items.
|
||||
# """
|
||||
# data = [
|
||||
# {
|
||||
# 'id': 0,
|
||||
# 'title': 'The electric kool-aid acid test',
|
||||
# 'author': 'Tom Wolfe'
|
||||
# }, {
|
||||
# 'id': 3,
|
||||
# 'title': 'Kafka on the shore',
|
||||
# 'author': 'Haruki Murakami'
|
||||
# }
|
||||
# ]
|
||||
# expected_errors = [
|
||||
# {},
|
||||
# {'non_field_errors': ['Cannot create a new item, only existing items may be updated.']}
|
||||
# ]
|
||||
# serializer = self.BookSerializer(self.books(), data=data, many=True)
|
||||
# self.assertEqual(serializer.is_valid(), False)
|
||||
# self.assertEqual(serializer.errors, expected_errors)
|
||||
|
||||
# def test_bulk_update_error(self):
|
||||
# """
|
||||
# Incorrect bulk update serialization should return error data.
|
||||
# """
|
||||
# data = [
|
||||
# {
|
||||
# 'id': 0,
|
||||
# 'title': 'The electric kool-aid acid test',
|
||||
# 'author': 'Tom Wolfe'
|
||||
# }, {
|
||||
# 'id': 'foo',
|
||||
# 'title': 'Kafka on the shore',
|
||||
# 'author': 'Haruki Murakami'
|
||||
# }
|
||||
# ]
|
||||
# expected_errors = [
|
||||
# {},
|
||||
# {'id': ['Enter a whole number.']}
|
||||
# ]
|
||||
# serializer = self.BookSerializer(self.books(), data=data, many=True, allow_add_remove=True)
|
||||
# self.assertEqual(serializer.is_valid(), False)
|
||||
# self.assertEqual(serializer.errors, expected_errors)
|
||||
|
|
|
@ -1,15 +0,0 @@
|
|||
# from django.test import TestCase
|
||||
# from rest_framework import serializers
|
||||
|
||||
|
||||
# class EmptySerializerTestCase(TestCase):
|
||||
# def test_empty_serializer(self):
|
||||
# class FooBarSerializer(serializers.Serializer):
|
||||
# foo = serializers.IntegerField()
|
||||
# bar = serializers.SerializerMethodField()
|
||||
|
||||
# def get_bar(self, obj):
|
||||
# return 'bar'
|
||||
|
||||
# serializer = FooBarSerializer()
|
||||
# self.assertEquals(serializer.data, {'foo': 0})
|
|
@ -38,353 +38,3 @@ class TestNestedSerializer:
|
|||
}
|
||||
serializer = self.Serializer()
|
||||
assert serializer.data == expected_data
|
||||
|
||||
# """
|
||||
# Tests to cover nested serializers.
|
||||
|
||||
# Doesn't cover model serializers.
|
||||
# """
|
||||
# from __future__ import unicode_literals
|
||||
# from django.test import TestCase
|
||||
# from rest_framework import serializers
|
||||
# from . import models
|
||||
|
||||
|
||||
# class WritableNestedSerializerBasicTests(TestCase):
|
||||
# """
|
||||
# Tests for deserializing nested entities.
|
||||
# Basic tests that use serializers that simply restore to dicts.
|
||||
# """
|
||||
|
||||
# def setUp(self):
|
||||
# class TrackSerializer(serializers.Serializer):
|
||||
# order = serializers.IntegerField()
|
||||
# title = serializers.CharField(max_length=100)
|
||||
# duration = serializers.IntegerField()
|
||||
|
||||
# class AlbumSerializer(serializers.Serializer):
|
||||
# album_name = serializers.CharField(max_length=100)
|
||||
# artist = serializers.CharField(max_length=100)
|
||||
# tracks = TrackSerializer(many=True)
|
||||
|
||||
# self.AlbumSerializer = AlbumSerializer
|
||||
|
||||
# def test_nested_validation_success(self):
|
||||
# """
|
||||
# Correct nested serialization should return the input data.
|
||||
# """
|
||||
|
||||
# data = {
|
||||
# 'album_name': 'Discovery',
|
||||
# 'artist': 'Daft Punk',
|
||||
# 'tracks': [
|
||||
# {'order': 1, 'title': 'One More Time', 'duration': 235},
|
||||
# {'order': 2, 'title': 'Aerodynamic', 'duration': 184},
|
||||
# {'order': 3, 'title': 'Digital Love', 'duration': 239}
|
||||
# ]
|
||||
# }
|
||||
|
||||
# serializer = self.AlbumSerializer(data=data)
|
||||
# self.assertEqual(serializer.is_valid(), True)
|
||||
# self.assertEqual(serializer.object, data)
|
||||
|
||||
# def test_nested_validation_error(self):
|
||||
# """
|
||||
# Incorrect nested serialization should return appropriate error data.
|
||||
# """
|
||||
|
||||
# data = {
|
||||
# 'album_name': 'Discovery',
|
||||
# 'artist': 'Daft Punk',
|
||||
# 'tracks': [
|
||||
# {'order': 1, 'title': 'One More Time', 'duration': 235},
|
||||
# {'order': 2, 'title': 'Aerodynamic', 'duration': 184},
|
||||
# {'order': 3, 'title': 'Digital Love', 'duration': 'foobar'}
|
||||
# ]
|
||||
# }
|
||||
# expected_errors = {
|
||||
# 'tracks': [
|
||||
# {},
|
||||
# {},
|
||||
# {'duration': ['Enter a whole number.']}
|
||||
# ]
|
||||
# }
|
||||
|
||||
# serializer = self.AlbumSerializer(data=data)
|
||||
# self.assertEqual(serializer.is_valid(), False)
|
||||
# self.assertEqual(serializer.errors, expected_errors)
|
||||
|
||||
# def test_many_nested_validation_error(self):
|
||||
# """
|
||||
# Incorrect nested serialization should return appropriate error data
|
||||
# when multiple entities are being deserialized.
|
||||
# """
|
||||
|
||||
# data = [
|
||||
# {
|
||||
# 'album_name': 'Russian Red',
|
||||
# 'artist': 'I Love Your Glasses',
|
||||
# 'tracks': [
|
||||
# {'order': 1, 'title': 'Cigarettes', 'duration': 121},
|
||||
# {'order': 2, 'title': 'No Past Land', 'duration': 198},
|
||||
# {'order': 3, 'title': 'They Don\'t Believe', 'duration': 191}
|
||||
# ]
|
||||
# },
|
||||
# {
|
||||
# 'album_name': 'Discovery',
|
||||
# 'artist': 'Daft Punk',
|
||||
# 'tracks': [
|
||||
# {'order': 1, 'title': 'One More Time', 'duration': 235},
|
||||
# {'order': 2, 'title': 'Aerodynamic', 'duration': 184},
|
||||
# {'order': 3, 'title': 'Digital Love', 'duration': 'foobar'}
|
||||
# ]
|
||||
# }
|
||||
# ]
|
||||
# expected_errors = [
|
||||
# {},
|
||||
# {
|
||||
# 'tracks': [
|
||||
# {},
|
||||
# {},
|
||||
# {'duration': ['Enter a whole number.']}
|
||||
# ]
|
||||
# }
|
||||
# ]
|
||||
|
||||
# serializer = self.AlbumSerializer(data=data, many=True)
|
||||
# self.assertEqual(serializer.is_valid(), False)
|
||||
# self.assertEqual(serializer.errors, expected_errors)
|
||||
|
||||
|
||||
# class WritableNestedSerializerObjectTests(TestCase):
|
||||
# """
|
||||
# Tests for deserializing nested entities.
|
||||
# These tests use serializers that restore to concrete objects.
|
||||
# """
|
||||
|
||||
# def setUp(self):
|
||||
# # Couple of concrete objects that we're going to deserialize into
|
||||
# class Track(object):
|
||||
# def __init__(self, order, title, duration):
|
||||
# self.order, self.title, self.duration = order, title, duration
|
||||
|
||||
# def __eq__(self, other):
|
||||
# return (
|
||||
# self.order == other.order and
|
||||
# self.title == other.title and
|
||||
# self.duration == other.duration
|
||||
# )
|
||||
|
||||
# class Album(object):
|
||||
# def __init__(self, album_name, artist, tracks):
|
||||
# self.album_name, self.artist, self.tracks = album_name, artist, tracks
|
||||
|
||||
# def __eq__(self, other):
|
||||
# return (
|
||||
# self.album_name == other.album_name and
|
||||
# self.artist == other.artist and
|
||||
# self.tracks == other.tracks
|
||||
# )
|
||||
|
||||
# # And their corresponding serializers
|
||||
# class TrackSerializer(serializers.Serializer):
|
||||
# order = serializers.IntegerField()
|
||||
# title = serializers.CharField(max_length=100)
|
||||
# duration = serializers.IntegerField()
|
||||
|
||||
# def restore_object(self, attrs, instance=None):
|
||||
# return Track(attrs['order'], attrs['title'], attrs['duration'])
|
||||
|
||||
# class AlbumSerializer(serializers.Serializer):
|
||||
# album_name = serializers.CharField(max_length=100)
|
||||
# artist = serializers.CharField(max_length=100)
|
||||
# tracks = TrackSerializer(many=True)
|
||||
|
||||
# def restore_object(self, attrs, instance=None):
|
||||
# return Album(attrs['album_name'], attrs['artist'], attrs['tracks'])
|
||||
|
||||
# self.Album, self.Track = Album, Track
|
||||
# self.AlbumSerializer = AlbumSerializer
|
||||
|
||||
# def test_nested_validation_success(self):
|
||||
# """
|
||||
# Correct nested serialization should return a restored object
|
||||
# that corresponds to the input data.
|
||||
# """
|
||||
|
||||
# data = {
|
||||
# 'album_name': 'Discovery',
|
||||
# 'artist': 'Daft Punk',
|
||||
# 'tracks': [
|
||||
# {'order': 1, 'title': 'One More Time', 'duration': 235},
|
||||
# {'order': 2, 'title': 'Aerodynamic', 'duration': 184},
|
||||
# {'order': 3, 'title': 'Digital Love', 'duration': 239}
|
||||
# ]
|
||||
# }
|
||||
# expected_object = self.Album(
|
||||
# album_name='Discovery',
|
||||
# artist='Daft Punk',
|
||||
# tracks=[
|
||||
# self.Track(order=1, title='One More Time', duration=235),
|
||||
# self.Track(order=2, title='Aerodynamic', duration=184),
|
||||
# self.Track(order=3, title='Digital Love', duration=239),
|
||||
# ]
|
||||
# )
|
||||
|
||||
# serializer = self.AlbumSerializer(data=data)
|
||||
# self.assertEqual(serializer.is_valid(), True)
|
||||
# self.assertEqual(serializer.object, expected_object)
|
||||
|
||||
# def test_many_nested_validation_success(self):
|
||||
# """
|
||||
# Correct nested serialization should return multiple restored objects
|
||||
# that corresponds to the input data when multiple objects are
|
||||
# being deserialized.
|
||||
# """
|
||||
|
||||
# data = [
|
||||
# {
|
||||
# 'album_name': 'Russian Red',
|
||||
# 'artist': 'I Love Your Glasses',
|
||||
# 'tracks': [
|
||||
# {'order': 1, 'title': 'Cigarettes', 'duration': 121},
|
||||
# {'order': 2, 'title': 'No Past Land', 'duration': 198},
|
||||
# {'order': 3, 'title': 'They Don\'t Believe', 'duration': 191}
|
||||
# ]
|
||||
# },
|
||||
# {
|
||||
# 'album_name': 'Discovery',
|
||||
# 'artist': 'Daft Punk',
|
||||
# 'tracks': [
|
||||
# {'order': 1, 'title': 'One More Time', 'duration': 235},
|
||||
# {'order': 2, 'title': 'Aerodynamic', 'duration': 184},
|
||||
# {'order': 3, 'title': 'Digital Love', 'duration': 239}
|
||||
# ]
|
||||
# }
|
||||
# ]
|
||||
# expected_object = [
|
||||
# self.Album(
|
||||
# album_name='Russian Red',
|
||||
# artist='I Love Your Glasses',
|
||||
# tracks=[
|
||||
# self.Track(order=1, title='Cigarettes', duration=121),
|
||||
# self.Track(order=2, title='No Past Land', duration=198),
|
||||
# self.Track(order=3, title='They Don\'t Believe', duration=191),
|
||||
# ]
|
||||
# ),
|
||||
# self.Album(
|
||||
# album_name='Discovery',
|
||||
# artist='Daft Punk',
|
||||
# tracks=[
|
||||
# self.Track(order=1, title='One More Time', duration=235),
|
||||
# self.Track(order=2, title='Aerodynamic', duration=184),
|
||||
# self.Track(order=3, title='Digital Love', duration=239),
|
||||
# ]
|
||||
# )
|
||||
# ]
|
||||
|
||||
# serializer = self.AlbumSerializer(data=data, many=True)
|
||||
# self.assertEqual(serializer.is_valid(), True)
|
||||
# self.assertEqual(serializer.object, expected_object)
|
||||
|
||||
|
||||
# class ForeignKeyNestedSerializerUpdateTests(TestCase):
|
||||
# def setUp(self):
|
||||
# class Artist(object):
|
||||
# def __init__(self, name):
|
||||
# self.name = name
|
||||
|
||||
# def __eq__(self, other):
|
||||
# return self.name == other.name
|
||||
|
||||
# class Album(object):
|
||||
# def __init__(self, name, artist):
|
||||
# self.name, self.artist = name, artist
|
||||
|
||||
# def __eq__(self, other):
|
||||
# return self.name == other.name and self.artist == other.artist
|
||||
|
||||
# class ArtistSerializer(serializers.Serializer):
|
||||
# name = serializers.CharField()
|
||||
|
||||
# def restore_object(self, attrs, instance=None):
|
||||
# if instance:
|
||||
# instance.name = attrs['name']
|
||||
# else:
|
||||
# instance = Artist(attrs['name'])
|
||||
# return instance
|
||||
|
||||
# class AlbumSerializer(serializers.Serializer):
|
||||
# name = serializers.CharField()
|
||||
# by = ArtistSerializer(source='artist')
|
||||
|
||||
# def restore_object(self, attrs, instance=None):
|
||||
# if instance:
|
||||
# instance.name = attrs['name']
|
||||
# instance.artist = attrs['artist']
|
||||
# else:
|
||||
# instance = Album(attrs['name'], attrs['artist'])
|
||||
# return instance
|
||||
|
||||
# self.Artist = Artist
|
||||
# self.Album = Album
|
||||
# self.AlbumSerializer = AlbumSerializer
|
||||
|
||||
# def test_create_via_foreign_key_with_source(self):
|
||||
# """
|
||||
# Check that we can both *create* and *update* into objects across
|
||||
# ForeignKeys that have a `source` specified.
|
||||
# Regression test for #1170
|
||||
# """
|
||||
# data = {
|
||||
# 'name': 'Discovery',
|
||||
# 'by': {'name': 'Daft Punk'},
|
||||
# }
|
||||
|
||||
# expected = self.Album(artist=self.Artist('Daft Punk'), name='Discovery')
|
||||
|
||||
# # create
|
||||
# serializer = self.AlbumSerializer(data=data)
|
||||
# self.assertEqual(serializer.is_valid(), True)
|
||||
# self.assertEqual(serializer.object, expected)
|
||||
|
||||
# # update
|
||||
# original = self.Album(artist=self.Artist('The Bats'), name='Free All the Monsters')
|
||||
# serializer = self.AlbumSerializer(instance=original, data=data)
|
||||
# self.assertEqual(serializer.is_valid(), True)
|
||||
# self.assertEqual(serializer.object, expected)
|
||||
|
||||
|
||||
# class NestedModelSerializerUpdateTests(TestCase):
|
||||
# def test_second_nested_level(self):
|
||||
# john = models.Person.objects.create(name="john")
|
||||
|
||||
# post = john.blogpost_set.create(title="Test blog post")
|
||||
# post.blogpostcomment_set.create(text="I hate this blog post")
|
||||
# post.blogpostcomment_set.create(text="I love this blog post")
|
||||
|
||||
# class BlogPostCommentSerializer(serializers.ModelSerializer):
|
||||
# class Meta:
|
||||
# model = models.BlogPostComment
|
||||
|
||||
# class BlogPostSerializer(serializers.ModelSerializer):
|
||||
# comments = BlogPostCommentSerializer(many=True, source='blogpostcomment_set')
|
||||
|
||||
# class Meta:
|
||||
# model = models.BlogPost
|
||||
# fields = ('id', 'title', 'comments')
|
||||
|
||||
# class PersonSerializer(serializers.ModelSerializer):
|
||||
# posts = BlogPostSerializer(many=True, source='blogpost_set')
|
||||
|
||||
# class Meta:
|
||||
# model = models.Person
|
||||
# fields = ('id', 'name', 'age', 'posts')
|
||||
|
||||
# serialize = PersonSerializer(instance=john)
|
||||
# deserialize = PersonSerializer(data=serialize.data, instance=john)
|
||||
# self.assertTrue(deserialize.is_valid())
|
||||
|
||||
# result = deserialize.object
|
||||
# result.save()
|
||||
# self.assertEqual(result.id, john.id)
|
||||
|
|
|
@ -165,17 +165,6 @@ class TestChoiceFieldChoicesValidate(TestCase):
|
|||
except serializers.ValidationError:
|
||||
self.fail("Value %s does not validate" % str(value))
|
||||
|
||||
# def test_nested_choices(self):
|
||||
# """
|
||||
# Make sure a nested value for choices works as expected.
|
||||
# """
|
||||
# f = serializers.ChoiceField(choices=self.CHOICES_NESTED)
|
||||
# value = self.CHOICES_NESTED[0][1][0][0]
|
||||
# try:
|
||||
# f.to_native(value)
|
||||
# except ValidationError:
|
||||
# self.fail("Value %s does not validate" % str(value))
|
||||
|
||||
|
||||
class RegexSerializer(serializers.Serializer):
|
||||
pin = serializers.CharField(
|
||||
|
|
Loading…
Reference in New Issue
Block a user