如何模拟Django测试的喜欢计数

发布于 2025-01-20 20:11:41 字数 2457 浏览 2 评论 0原文

我需要测试此观点:

class ShowHomePageView(views.TemplateView):
    template_name = 'home_page.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        books = Book.objects.prefetch_related('likes'). \
                    filter(owner__isnull=False). \
                    annotate(like_count=Count('likes')). \
                    order_by('-like_count', 'title'). \
                    all()[:3]
        context['books_to_show'] = books
        return context

这是我的模型:

class Book(models.Model):
    TITTLE_MAX_LENGTH = 64
    AUTHOR_MAX_LENGTH = 64
    UPLOAD_PICTURE_MAX_SIZE_IN_MB = 2

    title = models.CharField(
        max_length=TITTLE_MAX_LENGTH,
    )

    author = models.CharField(
        max_length=AUTHOR_MAX_LENGTH,
    )

    category = models.ForeignKey(
        to=Category,
        null=True,
        blank=True,
        default='',
        on_delete=models.SET_DEFAULT,
    )

    image = CloudinaryField(
        "Image",
        null=True,
        blank=True,
        transformation={"quality": "auto:eco"},
        overwrite=True,
    )

    owner = models.ForeignKey(
        to=get_user_model(),
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='own_books',
    )

    ex_owners = models.ManyToManyField(
        to=get_user_model(),
        related_name='ex_books',
        blank=True,

    )

    previous_owner = models.ForeignKey(
        to=get_user_model(),
        related_name='books_to_send',
        null=True,
        blank=True,
        on_delete=models.SET_NULL
    )

    next_owner = models.ForeignKey(
        to=get_user_model(),
        related_name='book_on_a_way',
        null=True,
        blank=True,
        on_delete=models.SET_NULL
    )

    likes = models.ManyToManyField(
        to=get_user_model(),
        related_name='liked_books',
        blank=True,
    )

    is_tradable = models.BooleanField(
        default=True,
    )

    @property
    def likes_count(self):
        return len(self.likes.all())

    def __str__(self):
        return f'"{self.title}" by {self.author}'

    class Meta:
        ordering = ['title']

    def get_absolute_url(self):
        return reverse('book_details', kwargs={'pk': self.pk})

我不知道如何测试该视图是否获得最喜欢的书籍最喜欢的书。我会很容易地创建一些书籍,但是我不知道如何嘲笑喜欢的价值。我可以手动创建很多用户将其添加到这本书中。likes,但希望还有另一种更聪明的方法可以做到这一点。你能给我一些线索吗?

I need to test this view:

class ShowHomePageView(views.TemplateView):
    template_name = 'home_page.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        books = Book.objects.prefetch_related('likes'). \
                    filter(owner__isnull=False). \
                    annotate(like_count=Count('likes')). \
                    order_by('-like_count', 'title'). \
                    all()[:3]
        context['books_to_show'] = books
        return context

This is my model:

class Book(models.Model):
    TITTLE_MAX_LENGTH = 64
    AUTHOR_MAX_LENGTH = 64
    UPLOAD_PICTURE_MAX_SIZE_IN_MB = 2

    title = models.CharField(
        max_length=TITTLE_MAX_LENGTH,
    )

    author = models.CharField(
        max_length=AUTHOR_MAX_LENGTH,
    )

    category = models.ForeignKey(
        to=Category,
        null=True,
        blank=True,
        default='',
        on_delete=models.SET_DEFAULT,
    )

    image = CloudinaryField(
        "Image",
        null=True,
        blank=True,
        transformation={"quality": "auto:eco"},
        overwrite=True,
    )

    owner = models.ForeignKey(
        to=get_user_model(),
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='own_books',
    )

    ex_owners = models.ManyToManyField(
        to=get_user_model(),
        related_name='ex_books',
        blank=True,

    )

    previous_owner = models.ForeignKey(
        to=get_user_model(),
        related_name='books_to_send',
        null=True,
        blank=True,
        on_delete=models.SET_NULL
    )

    next_owner = models.ForeignKey(
        to=get_user_model(),
        related_name='book_on_a_way',
        null=True,
        blank=True,
        on_delete=models.SET_NULL
    )

    likes = models.ManyToManyField(
        to=get_user_model(),
        related_name='liked_books',
        blank=True,
    )

    is_tradable = models.BooleanField(
        default=True,
    )

    @property
    def likes_count(self):
        return len(self.likes.all())

    def __str__(self):
        return f'"{self.title}" by {self.author}'

    class Meta:
        ordering = ['title']

    def get_absolute_url(self):
        return reverse('book_details', kwargs={'pk': self.pk})

I have no idea how to test if the view gets the top 3 most liked books. I will easily create some books, but I do not know how to mock the value for likes count. I could create manually a lot of users add them to the book.likes but hope there is another smarter way to do it. Can you give me some clues?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光清浅 2025-01-27 20:11:41

您可以使用 model_mommy 或/factoryboy.readthedocs.io/en/stable/“ rel =“ nofollow noreferrer”> factory_boy 创建一个虚拟对象。创建一些对象后,您可以模拟这些功能。

with patch('path_your_model.Book.likes_count', return_value=3):
     # your test code

还有一件事是一个ORM函数来计算对象。

@property
def likes_count(self):
    return self.likes.all().count()

You can use the model_mommy or factory_boy to create a dummy objects. After the create some objects you can mock the functions.

with patch('path_your_model.Book.likes_count', return_value=3):
     # your test code

and one more thing there is an orm function to count objects.

@property
def likes_count(self):
    return self.likes.all().count()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文