我不知道如何使用unittests测试这些视图

2024-04-24 01:13:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用unittest来测试这段代码。请帮我弄清楚它,并说明它们是如何被测试的

def post(self, request, pk):
    form = ReviewForm(request.POST)
    movie = Movie.objects.get(id=pk)
    if form.is_valid():
        form = form.save(commit=False)
        if request.POST.get("parent", None):
            form.parent_id = int(request.POST.get("parent"))
        form.movie = movie
        form.save()
    return redirect(movie.get_absolute_url())

Tags: 代码selfformidgetifrequestsave
1条回答
网友
1楼 · 发布于 2024-04-24 01:13:04

Django的单元测试使用Python标准库模块:unittest。此模块使用基于类的方法定义测试

要使用它,请转到应用程序文件夹中的test.py。在那里,您可以开始编写测试:

  1. 您需要做的第一件事是导入TestCase和要测试的模型,例如:

    从django.test导入TestCase 从myapp.models导入帖子

  2. 其次,您需要编写测试。想想,你需要测试什么?例如,如果它是一个创建帖子的表单,则需要测试该帖子是否已创建并保存在数据库中

为此,您需要设置初始状态,以便在安全环境中运行测试

让我们以这篇文章为例:

from django.test import TestCase
from myapp.models import Post

class CreateNewPostsTest(TestCase):
    """
    This class contains tests that test if the posts are being correctly created
    """

   def setUp(self):
        """Set up initial database to run before each test, it'll create a database, run a test and then delete it"""

        # Create a new user to test
        user1 = User.objects.create_user(
            username="test_user_1", email="test1@example.com", password="falcon"
        )

        # Create a new post
        post1 = NewPosts.objects.create(
            user_post=user1,
            post_time="2020-09-23T20:16:46.971223Z",
            content='This is a test to check if a post is correctly created',
        )
  1. 上面的代码设置了一个安全状态来测试我们的代码。现在我们需要编写一个测试检查,它将运行一个测试,看看我们在setUp定义的代码是否达到了我们预期的效果

因此,在我们的class CreateNewPostsTest中,您需要定义一个新函数来运行测试:

def test_create_post_db(self):
    """Test if the new posts from different users where saved"""
    self.assertEqual(NewPosts.objects.count(), 1)

这段代码将运行一个assertEqual,它将检查数据库中的对象计数是否等于1(因为我们刚刚在设置中创建了一篇文章)

  1. 现在,您需要使用以下工具运行测试:

    python manage.py测试

它将运行测试,您将在终端中看到测试是否失败

在您的情况下,您可以对您的电影模型执行相同的操作

您可以在Django文档中找到有关测试的更多信息:https://docs.djangoproject.com/en/3.1/topics/testing/overview/

相关问题 更多 >