我目前正在为我的Django webapp编写单元测试,并遇到了一个绊脚石。
我的模特:
class Employment(models.Model):
applicant = models.ForeignKey(Applicant)
company = models.CharField(max_length=50)
town = models.CharField(max_length=50)
salary = models.CharField(max_length=50)
job_title = models.CharField(max_length=50)
responsibilities = models.CharField(max_length=100)
date_from = models.DateField('Date From')
date_to = models.DateField('Date To')
reason_for_leaving = models.CharField(max_length=50)
我的表格:
class EmploymentForm(forms.ModelForm):
error_css_class = 'error' #set some css when an error
company = forms.CharField(label="Company/Agency")
town = forms.CharField(label="Town/City")
salary = forms.CharField(label="Salary/Pay rate")
date_from = forms.DateField(('%d/%m/%Y',), widget=forms.DateInput(format='%d/%m/%Y', attrs={'placeholder':'dd/mm/yyyy'}))
date_to = forms.DateField(('%d/%m/%Y',), widget=forms.DateInput(format='%d/%m/%Y', attrs={'placeholder':'dd/mm/yyyy'}))
class Meta:
model = Employment
我的测试:
"""
Complete employment form passes validation
"""
def test_employment_form_complete(self):
applicant = Applicant(job_id=1)
data = {
'company': 'test company',
'town': 'test town',
'salary': '1000000',
'job_title': 'test job name',
'responsibilities': 'test responsibilities',
'date_from': '01/01/1990',
'date_to': '01/02/1991',
'reason_for_leaving': 'test reason for leaving'
}
employment_form = EmploymentForm(instance=applicant, data=data)
result = employment_form.is_valid()
print "errors %s" % employment_form.errors
self.assertEqual(result, True)
如果我像这样运行测试,我得到:
<ul class="errorlist"><li>applicant<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
如果我添加:
'applicant': applicant
我的数据对象抱怨它需要是一个int。
如果我添加:
'applicant': 1
(或其他整数)
它返回:
<ul class="errorlist"><li>applicant<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>
这是可以理解的。
我该如何解决这个问题?什么是最佳做法?
此致
克里斯。
答案 0 :(得分:1)
我认为你应该致电applicant.save()
您创建新对象,但未将其保存到数据库。在测试django时创建“临时”数据库。
还添加到数据字典'申请人':1。
PS。确保使用外键= 1 !!
创建申请人对象完全正常工作的代码。
def test_employment_form_complete(self):
"""
Complete employment form passes validation
"""
applicant = Applicant(job_id=1)
applicant.save()
data = {
'applicant': 1,
'company': 'test company',
'town': 'test town',
'salary': '1000000',
'job_title': 'test job name',
'responsibilities': 'test responsibilities',
'date_from': '01/01/1990',
'date_to': '01/02/1991',
'reason_for_leaving': 'test reason for leaving'
}
employment_form = EmploymentForm(instance=applicant, data=data)
result = employment_form.is_valid()
print "errors %s" % employment_form.errors
self.assertEqual(result, True)