我一直试图在Django中测试一个表单ChoiceField
。
我有Form
个ChoiceField
:
class PickPlanForm(forms.Form):
"Set the `plan` session cookie for choice here."
plan_choices = Plan.objects.get_choices()
# Field
plan = forms.ChoiceField(required=True, choices=plan_choices)
这是我的plan_choices
:
[('Bronze', 'Bronze ($10.00 per month)'),
('Silver', 'Silver ($20.00 per month)')]
我试图通过以下方式测试它:
response = self.client.post(reverse('payment:register_step3'),
{'plan': 'Bronze'}, follow=True)
self.assertRedirects(response, reverse('payment:register_step4'))
但是,在运行我的测试时,我不断收到错误回溯:
Traceback (most recent call last):
File "/Users/aaron/Documents/djcode/textress_concierge/textress/main/tests/test_views.py", line 170, in test_register_step3
self.assertRedirects(response, reverse('payment:register_step4'))
File "/Users/aaron/Documents/virtualenvs/textress/lib/python3.4/site-packages/django/test/testcases.py", line 263, in assertRedirects
(response.status_code, status_code))
AssertionError: False is not True : Response didn't redirect as expected: Response code was 200 (expected 302)
我正在使用:
Django 1.6.8
Python 3.4
我认为这很容易让我失踪?
谢谢
修改:添加视图
from django.views.generic import FormView
from braces.views import LoginRequiredMixin
class PickPlanView(LoginRequiredMixin, FormView):
"""
Step #3 of Registration
Pick a Plan, and save the Plan as a `session cookie` before creating
the Stipe Customer/Subscription using the Plan Choice.
"""
template_name = 'main/hotel_form.html'
form_class = PickPlanForm
success_url = reverse_lazy('payment:register_step4')
authenticated_redirect_url = settings.VERIFY_LOGOUT_URL
def get_form_kwargs(self):
"""Add the `request` Obj to Form, so I can set the PlanPick as a
session cookie for the time being."""
kwargs = super().get_form_kwargs()
kwargs['request'] = self.request
return kwargs
观点说明:
它只接受表格选择。
我手动测试它时有效。
我只是遇到了Django ChoiceField Test
部分的问题,因为我之前没有对ChoiceField
进行过测试。
谢谢
答案 0 :(得分:1)
如果我发布无效选项,我可以以完全相同的方式使测试失败。发布 Bronze 会通过测试,但我在form
类中选择了硬编码,并且不会从数据库中动态获取它们。
让我想一想,如果计划存在于单元测试的数据库中(或者在模拟的queryset
中),那么它们是从Plan.objects.get_choices()
正确获取的吗?