Django FactoryBoy TestCase处理嵌套对象创建

时间:2019-07-13 11:39:52

标签: django django-rest-framework factory django-testing django-tests

我正在尝试使用django factory编写TestCase,这有点使测试用例无法编写。

这是我下面的models.py

class Author(models.Model):
    name = models.CharField(max_length=25)

    def __str__(self):
        return self.name

class Book(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author')
    title = models.CharField(max_length=200)
    body = models.TextField()

    def __str__ (self):
        return self.title

这是我下面的tests.py

from django.test import TestCase
from library.models import Author, Book
import factory

# Create factory for model
class AuthorFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Author
    name = 'author name'

class BookFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Book
    author = factory.SubFactory(AuthorFactory)
    title = 'i am title'
    body = 'i am body'


# Start TestCase here

class TestSingleBook(TestCase):
    def setUp(self):
        self.author = AuthorFactory.create_batch(
            10,
            name='Jhon Doe'
        )
        self.book = BookFactory.create_batch(
            author=self.author
        )

    def test_single_book_get(self):
        # compare here

上面的代码,我的测试用例类是class TestSingleBook(TestCase):,我希望你注意到了。。

我想创建10位作者,并与那10位作者一起创建10本书,然后在assertEqual

中进行比较

如果我与一位作者共同创作多本书,则可以轻松进行测试,但我不想要...

我的问题是嵌套/多个...

创建多位作者,然后与这些作者创建多本书...

有人解决过这种问题吗?

在这种情况下,有人可以帮助我吗?如果您没有得到所有这些,请随时向我询问。

1 个答案:

答案 0 :(得分:0)

不太确定这是否是您想要的,因为我无法真正理解您在测试用例中要比较的内容。但是对于要创建10名作者和10本书的声明,进行这种创建的一种方法就是使用for循环:

self.author = AuthorFactory.create_batch(10, name='Jhon Doe')
for author in self.author:
    BookFactory.create(author=author)

当然,这不会获得使用create_batch的效率。如果仍要使用create_batch,则可以使用django ORM关系表示:

BookFactory.create_batch(
    10,
    author__name='Jhon Doe',
    title=<your title>,
    body=<your body>)

请注意,由于您已经在AuthorFactory.create()中将author声明为SubFactory,因此无需调用BookFactory。第二个代码将创建10个Book对象,其中包含10个不同的Author对象,并且所有Author对象都具有相同的名称“ Jhon Doe”。