如何测试get_absolute_url在CreateView之后是否将我重定向到所需的网址

时间:2019-06-07 15:59:12

标签: django django-testing

有3个模型,每个模型都有3个CreateView。并且我想在填写表格后测试重定向。

我尝试编写3个测试,但是其中2个面临失败。但是该应用程序可以在浏览器中正常运行。

所有模型都具有此get_absolute_url方法

def get_absolute_url(self):
        return reverse('foo', kwargs = {'pk':self.pk})

上述模型的三个创建视图就是这样

class foo(CreateView):
    form_class = bar
    template_name = 'xxx.html'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

此测试有效

class Test_get_absolute_url(TestCase):
   def test_electronical_GAU(self):
       client = Client()
       create_electronical_ad_path = reverse_lazy('create_electronical_ad')
       User.objects.create(username = 'user1', password = 'TESTuSER1234')
       user = User.objects.get(username = 'user1')
       client.force_login(user)
       form = {'title':'title', 'price':123, 'location':20, 'tag':1,'description':'description'}
       response = client.post(create_electronical_ad_path, form)
       expected_url = reverse_lazy('electronical_detail', kwargs = {'pk':1})
       self.assertRedirects(response, expected_url)

这不是

def test_viechle_GAU(self):
        client = Client()
        create_viechle_ad_path = reverse_lazy('create_viechle_ad')
        User.objects.create(username = 'user1', password = 'TESTuSER1234')
        user = User.objects.get(username = 'user1')
        client.force_login(user)
        form = {'title':'title', 'price':123, 'location':20, 'produced':2019, 'color':'color', 'color': 'red' ,'description':'description'}
        response = client.post(create_viechle_ad_path, form)
        expected_url = reverse_lazy('viechle_detail', kwargs = {'pk':1})
        self.assertRedirects(response, expected_url)

这是错误

AssertionError: [] is not true : Response didn't redirect as expected: Response code was 200 (expected 302)

0 个答案:

没有答案