Django表格清洁方法测试错误

时间:2015-04-25 23:56:29

标签: python django forms testing

我正在测试我之前写过的表单。出于某种原因,测试不会通过。就像表单忽略了我传递的数据一样,我不明白为什么。回溯告诉我,表单的clean方法中的用户变量是None,尽管用户肯定会传递给表单。追溯:

  

......干净利落       如果user.pk不是userwebsite.user.pk:AttributeError:' NoneType'对象没有属性' pk'

表格:

class CreateAuditForm(forms.Form):
    user = forms.ModelChoiceField(queryset=User.objects.all(), widget=HiddenInput)
    website = forms.ModelChoiceField(queryset=UserWebsite.objects.all(), widget=HiddenInput)
    emails = forms.CharField(
        max_length=250,
        required=False
    )

    def clean_user(self):
        user = self.cleaned_data.get('user', None)
        if not user.groups.filter(name__iexact='subscribed').exists() and not user.groups.filter(name__iexact='addon').exists():
            raise forms.ValidationError(_("You must have an active subscription to request \
website audits. Please try again after subscribing to us."))
        return user

    def clean(self):
        data = self.cleaned_data
        user = data.get('user')
        userwebsite = data.get('website', None)

        if userwebsite.user:
            if user.pk is not userwebsite.user.pk:
                raise forms.ValidationError(_("Sorry, try again."))
        elif userwebsite.addon:
            if user.pk is not userwebsite.addon.pk:
                raise forms.ValidationError(_("Sorry, try again."))
        return self.cleaned_data

    def save(self):
        # Action

测试:

class CreateAuditFormTestCase(TestCase):

    def setUp(self):
        super(CreateAuditFormTestCase, self).setUp()
        self.form = CreateAuditForm
        ...
        self.website = Website.objects.create(
            title="permanence",
            url="https://www.badabuyhere.com",
            display="www.bababuyhere.com")
        self.unsubscriber = User.objects.create(
            username="adiagojesse",
            first_name="adiago",
            last_name="jesse",
            email="bannerfare@coldmount.com",
            password="tigermountainvalley"
        )
        self.unsubscriberwebsite = UserWebsite.objects.create(
            user=self.unsubscriber,
            website=self.website,
            is_competitor=False
        )

    ...
    def test_user_validation(self):
        data = {
            "user":self.unsubscriber.pk,
            "website":self.unsubscriberwebsite.pk,
            "emails":"john@gmail.com, jeff@gmail.com"
        }
        self.assertTrue(self.unsubscriber)
        self.assertTrue(self.unsubscriberwebsite)
        audit = self.form(data)
        self.assertEqual(audit.is_valid(), False)

这可能是一个我无法接受的简单问题,这让我感到沮丧,哈哈。帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我的猜测是CreateAuditForm.cleanuserNone,因为clean_user提出ValidationErrorValidationError来自于用户没有他需要的组的事实。

我看到的另一个问题是,为了测试Django中模型实例之间的相等性,您不应该使用主键,而是使用==而不是is直接使用实例进行测试。 (有关is==

的详情,请参阅https://stackoverflow.com/a/13650309/1644198

示例:

if user != userwebsite.user:
    # etc...