django-rest-framework/tests/generic_relations/test_generic_relations.py

67 lines
2.1 KiB
Python
Raw Normal View History

2014-10-08 14:22:10 +04:00
from __future__ import unicode_literals
2015-06-25 23:55:51 +03:00
2014-10-08 14:22:10 +04:00
from django.test import TestCase
2015-06-25 23:55:51 +03:00
2014-10-08 14:22:10 +04:00
from rest_framework import serializers
from .models import Bookmark, Note, Tag
2014-10-08 14:22:10 +04:00
class TestGenericRelations(TestCase):
def setUp(self):
self.bookmark = Bookmark.objects.create(url='https://www.djangoproject.com/')
Tag.objects.create(tagged_item=self.bookmark, tag='django')
Tag.objects.create(tagged_item=self.bookmark, tag='python')
self.note = Note.objects.create(text='Remember the milk')
Tag.objects.create(tagged_item=self.note, tag='reminder')
def test_generic_relation(self):
"""
Test a relationship that spans a GenericRelation field.
IE. A reverse generic relationship.
"""
class BookmarkSerializer(serializers.ModelSerializer):
tags = serializers.StringRelatedField(many=True)
class Meta:
model = Bookmark
fields = ('tags', 'url')
serializer = BookmarkSerializer(self.bookmark)
expected = {
'tags': ['django', 'python'],
'url': 'https://www.djangoproject.com/'
}
assert serializer.data == expected
2014-10-08 14:22:10 +04:00
def test_generic_fk(self):
"""
Test a relationship that spans a GenericForeignKey field.
IE. A forward generic relationship.
"""
class TagSerializer(serializers.ModelSerializer):
tagged_item = serializers.StringRelatedField()
class Meta:
model = Tag
fields = ('tag', 'tagged_item')
serializer = TagSerializer(Tag.objects.all(), many=True)
expected = [
{
'tag': 'django',
'tagged_item': 'Bookmark: https://www.djangoproject.com/'
},
{
'tag': 'python',
'tagged_item': 'Bookmark: https://www.djangoproject.com/'
},
{
'tag': 'reminder',
'tagged_item': 'Note: Remember the milk'
}
]
assert serializer.data == expected