我遇到了一个问题,将用户变量泄漏到注册表单上,允许用户在创建用户时进行设置。
我可以通过测试确保再次无法实现吗?
例如,我不希望用户设置自己的'coupon_code'。我将如何测试?
Accounts / forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import User
class RegisterUserForm(UserCreationForm):
email = forms.EmailField(required=True, help_text='Required.')
class Meta(UserCreationForm.Meta):
model = User
fields = ('username', 'password1', 'password2', 'email')
exclude = ('coupon_code',)
帐户/测试/test_forms.py:
from django.test import TestCase
from Accounts.forms import RegisterUserForm, UpdateUserForm
# Create your tests here.
class RegisterUserFormTest(TestCase):
#@classmethod
#def setUpTestData(cls):
# Set up non-modified objects used by all test methods
def valid_data(self):
return {'username':'abc', 'email':'[email protected]', 'password1': 'test123hello', 'password2':'test123hello'}
def test_register_user_form_cannot_set_coupon_code(self):
data = self.valid_data()
data['coupon_code'] = '42'
form = RegisterUserForm(data=data)
self.assertFalse(form.is_valid())
当前上述测试失败,因为即使存在排除字段,该表单也被视为有效
据我了解,is_valid()
方法将忽略传递给Form的额外数据。如果is_valid()
返回True
,则仅表示数据对指定字段有效,并且只有这些字段才会在cleaned_data词典(Django docs about this)中。
我认为您要执行的测试必须在使用此表单的视图函数上完成。它可能看起来像这样:
from django.test import Client
def test_your_user_creation_view(self):
c = Client()
c.post(reverse(<your view name>),<valid data with 'coupon_code':42>)
new_user = User.objects.get(username='abc')
self.assertTrue(new_user.coupon_code != '42')
self.assertEqual(new_user.coupon_code,<your default value for coupon_code>)