如何在django中测试使用post请求的视图?

时间:2017-04-19 16:45:30

标签: django django-models django-views http-post django-testing

这是我的观点(简化):

@login_required(login_url='/try_again')
def change_bar(request):
    foo_id = request.POST['fid']
    bar_id = request.POST['bid']
    foo = models.Foo.objects.get(id=foo_id)
    if foo.value > 42:
            bar = models.Bar.objects.get(id=bar_id)
            bar.value = foo.value
            bar.save()
    return other_view(request)

现在我想检查这个视图是否正常工作(在这个简化的模型中,如果Bar实例在应该的时候改变了值)。我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

我将假设您的意思是自动化测试,而不仅仅是检查帖子请求是否有效。如果你的意思是后者,只需检查执行请求并检查shell或管理员中相关FooBar的值。

发送POST次请求的最佳方式是使用Client。假设视图的名称为my_view

from django.test import Client
from django.urls import reverse

c = Client()
c.post(reverse('my_view'), data={'fid':43, 'bid':20})

但是您仍然需要数据库中的一些初始数据,并且您需要检查是否已经进行了预期的更改。您可以在此处使用TestCase

from django.test import TestCase, Client
from django.urls import reverse

FooBarTestCase(TestCase):

def setUp(self):
    # create some foo and bar data, using foo.objects.create etc
    # this will be run in between each test - the database is rolled back in between tests

def test_bar_not_changed(self):
    # write a post request which you expect not to change the value 
    # of a bar instance, then check that the values didn't change
    self.assertEqual(bar.value, old_bar.value)

def test_bar_changes(self):
    # write a post request which you expect to change the value of 
    # a bar instance, then assert that it changed as expected
    self.assertEqual(foo.value, bar.value)

我觉得有用的设置一些数据以便更轻松地执行测试的库是FactoryBoy。在为了测试目的而创建FooBar的新实例时,它减少了样板。另一个选择是编写灯具,但我发现如果您的模型发生变化则灵活性会降低。

如果您想了解有关python测试的更多信息,我还建议this book。它是面向django的,但这些原则适用于其他框架和上下文。

编辑:添加了关于工厂手册的建议和链接到书籍

答案 1 :(得分:0)

你可以试试" print"代码之间的语句,看看是否保存了正确的值。也用于更新,而不是使用" get"然后保存它(bar.save())你可以使用" filter"和"更新"方法

@login_required(login_url='/try_again')
def change_bar(request):
foo_id = request.POST['fid']
bar_id = request.POST['bid']
foo = models.Foo.objects.get(id=foo_id)
if foo.value > 42:
        models.Bar.objects.filter(id=bar_id).update(value=foo.value)
        #bar.value = foo.value
        #bar.save()
return other_view(request)