在测试Django Rest Framework时创建超链接关系

时间:2016-08-21 18:37:49

标签: django unit-testing testing django-rest-framework

在为Django Rest Framework编写测试时,如何创建超链接关系?

我尝试使用相关的Bar对象创建Foo对象,但我不确定如何才能最有效地创建该关系。

# models.py

import uuid

from django.db import models

class Foo(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4)
    bar = models.ForeignKey('Bar')

class Bar(models.Model):
    BarUUID = models.UUIDField(primary_key=True, default=uuid.uuid4
# serializers.py

from rest_framework import serializers
from myapp.models import Bar, Foo

class FooSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Foo
        fields = ('url', 'id', 'bar')

class BarSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Bar
        fields = ('url', 'BarUUID')
# views.py
class FooViewSet(viewsets.ModelViewSet):
    queryset = Foo.objects.all()
    serializer_class = FooSerializer

class BarViewSet(viewsets.ModelViewSet):
    queryset = Bar.objects.all()
    serializer_class = BarSerializer
# urls.py

from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'foos', views.FooViewSet)
router.register(r'bars', views.BarViewSet)
# tests.py

from rest_framework.reverse import reverse
from rest_framework.test import APITestCase

class FooTests(APITestCase):
    def test_create_foo(self):
        bar = Bar.objects.create()

        url = reverse('foo-list')
        data = {
            'bar': # how do I get the URL?
        }

        response = self.client.post(url, data, format='json')

2 个答案:

答案 0 :(得分:2)

您可以使用序列化程序来获取它。

像这样:

from django.test.client import RequestFactory

from your_app.serializers import BarSerializer

context = {'request': RequestFactory().get('/')}
bar_serializer = BarSerializer(bar, context=context)
bar_serializer.data['url']

答案 1 :(得分:1)

直接前进,没有序列化器:

url = 'http://testserver' + reverse('bar-detail', kwargs={'pk': bar.pk})