我不知道如何使用单元测试来测试这些视图

I can't figure out how to test these views using unittests

我需要使用 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())

Django 的单元测试使用 Python 标准库模块:unittest。该模块使用 class-based 方法定义测试。

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

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

    从django.test导入测试用例 从 myapp.models 导入 Post

  2. 其次,您需要编写测试。想一想,你需要测试什么?比如创建post的表单,需要测试post是否创建并保存在数据库中。

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

我们以post为例:

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(因为我们刚刚在 setUp 中创建了一个 post ).

  1. 现在您需要 运行 测试:

    pythonmanage.py测试

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

对于您的情况,您可以对 Movie 模型执行相同的操作。

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