Python 我能';我不知道如何使用unittests测试这些视图
我需要使用unittest来测试这段代码。请帮我弄清楚它,并说明它们是如何被测试的Python 我能';我不知道如何使用unittests测试这些视图,python,django,unit-testing,django-views,django-unittest,Python,Django,Unit Testing,Django Views,Django Unittest,我需要使用unittest来测试这段代码。请帮我弄清楚它,并说明它们是如何被测试的 def post(自我、请求、主键): 表单=审阅表单(request.POST) movie=movie.objects.get(id=pk) 如果form.is_有效(): form=form.save(commit=False) 如果request.POST.get(“父”,无): form.parent_id=int(request.POST.get(“parent”)) 电影 form.save() 返
def post(自我、请求、主键):
表单=审阅表单(request.POST)
movie=movie.objects.get(id=pk)
如果form.is_有效():
form=form.save(commit=False)
如果request.POST.get(“父”,无):
form.parent_id=int(request.POST.get(“parent”))
电影
form.save()
返回重定向(movie.get\u absolute\u url())
Django的单元测试使用Python标准库模块:unittest。此模块使用基于类的方法定义测试
要使用它,请转到应用程序文件夹中的test.py。在那里,您可以开始编写测试:
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',
)
setUp
中定义的代码是否达到了我们预期的效果类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(因为我们刚刚在设置中创建了一篇文章)