如何模拟Django Rest Framework视图的get_object方法?

时间:2018-09-10 16:33:12

标签: django django-rest-framework mocking factory-boy

我正在使用Django中的FactoryBoy的build(而不是create)方法。这样会创建对象而不将其存储在数据库中。

因此,为了使视图的测试能够正常工作,我需要修补与数据库有关的方法。

这是一些代码...

models.py:

class Book(models.Model):
  title = models.CharField(max_length=100)

serializers.py:

class BookSerializer(serializers.ModelSerializer):
  class Meta:
    model = Book
    fields = ('name')

views.py:

class BookViewSet(viewsets.ModelViewSet):

    def get_queryset(self):
        return Book.objects.all()

    def get_serializer_class(self):
         return BookSerializer

tests.py:

class BookFactory(factory.DjangoModelFactory):
  title = factory.Faker('sentence', nb_words=4)
  class Meta:
    model = "Book"

def my_test():
  client = APIClient()
  books = BookFactory.build_batch(10)
  list_url = reverse("books-list")
  with patch.object(BookViewSet, "get_queryset", return_value=books):
    list_url = reverse("books-list")
    response = client.get(list_url)
    # this works
    assert response.content = <a list of books> 
  with patch.object(BookViewSet, "get_object", return_value=books[0]):
    detail_url = reverse("books-detail", args=123)
    response = client.get(detail_url)
    # this is always empty..
    assert response.content == <a book>

无论我尝试什么,细节视图始终返回空JSON。我使用patch错了吗?

1 个答案:

答案 0 :(得分:1)

检索列表时(使用get_queryset时),我遇到了同样的问题。除了传递列表外,还应传递一个查询集作为return_value。

.git/packed-refs