社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

如何在Django中测试create函数?

Brocante • 5 年前 • 1447 次点击  
# my .views
def post_create_view(request):
    form = PostModelForm(request.POST or None)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.user = request.user
        obj.save()
        form = PostModelForm()
    context = {'form': form}
    return render(request, 'form.html', context)

# my .urls
path('create/', post_create_view, name='create')

# my .test

class TestViews(TestCase):

    def setUp(self):
        self.client = Client()
        self.create_url = reverse('posts:create')
        self.user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
        self.post1 = Post.objects.create(user=self.user, title='testpost', content='fgh')
        self.query = Post.objects.all()

    def test_blog_create_POST(self):
# this is where the error surely is
        response = self.client.post(self.create_url, {'title': 'testpost2', 'content': 'asd'})
        self.assertEqual(response.status_code, 302)
# this is where the test fail
        self.assertEqual(self.query.last().title, "testpost2")

“testpost2”无法创建,但我的表单工作正常。如何模拟测试用例中的输入?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55120
 
1447 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Charnel
Reply   •   1 楼
Charnel    5 年前

如果表单无效,它只是在页面上重新呈现表单-这将生成状态200,而不是302。另外,在表单无效的情况下,不清楚为什么要发送重定向状态。

form errors 在你的模板中。或者,如果你认为在你的情况下重定向是一个更好的选择,如果 is_valid() redirect .