Django测试不会接受测试用户

时间:2016-04-11 13:38:30

标签: python django django-testing

我目前正在尝试为我创建的模拟网站创建Django测试。
这是我的测试:

class ListingsTestCase(TestCase):
    def test_listing(self):
        user = User.objects.create_user(username='test')
        user.set_password('test')
        user.save()

        c = Client()
        c.login(username='test', password='test')
        category = Category.objects.get_or_create(name='test')

        t_listing = {
                    'title': 'Test',
                    'email': 'test@test.com',
                    'phone_number': '4057081902',
                    'description': 'Test',
                    'category': category,
                    'user': user,
                    }

        form = ListingForm(data=t_listing)
        self.assertEqual(form.errors, {})
        self.assertEqual(form.is_valid(),True)

我的模特:

class Listing(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length = 200)
    email = models.EmailField(max_length=50)
    phone_number = models.CharField(max_length=12, default='')
    listing_price = models.IntegerField(blank=True, null=True)
    image = models.FileField(upload_to='listing_images')
    description = models.TextField()
    created_date = models.DateTimeField(auto_now=True)
    category = models.ForeignKey('Category', null=True)

    def __str__(self):
        return self.title

这是我的ListingForm:

class ListingForm(forms.ModelForm):
    image = forms.FileField(required=False)
    class Meta:
        model = Listing
        fields = [
            'user',
            'title',
            'email',
            'phone_number',
           'description',
            'listing_price',
            'image',
            'category',
        ]
        widgets = {'user': forms.HiddenInput()}

这是我得到的错误:

FAIL: test_listing (seller.tests.ListingsTestCase)
Traceback (most recent call last):
File "/home/local/CE/mwilcoxen/project/hermes/seller/tests.py", line 35, in test_listing
self.assertEqual(form.errors, {})
AssertionError: {'category': [u'Select a valid choice. That choice is not one of the available choices.'], 'user': [u'Select a valid choice. That choice is not one of the available choices.']} != {}

所以我使用我的第一个assertEquals能够看到什么是抛出错误,并且我使用了一些断点来知道我的测试用户能够登录,但由于某种原因它只是不起作用。如果有人能给我一些很好的帮助。

1 个答案:

答案 0 :(得分:1)

尝试使用usercategory的ID,而不是实际的对象。

t_listing = {
    'title': 'Test',
    'email': 'test@test.com',
    'phone_number': '4057081902',
    'description': 'Test',
    'category': category.id,
    'user': user.id,

}

请注意,get_or_create会返回一个元组,因此您应该将该行更改为:

category, created = Category.objects.get_or_create(name='test')