我有一個models.py像這樣:Django的 - 讓在測試中的用戶對象
from django.db import models
from django.contrib.auth.models import User
# everything has a colour...
class Colour(models.Model):
colour = models.CharField(max_length=100)
def __unicode__(self):
return self.colour
# a thing can have a colour...
class Thing(models.Model):
name = models.CharField(max_length=155)
colour = models.ForeignKey(Colour)
description = models.CharField(max_length=255)
def __unicode__(self):
return self.name
# a user can save his choices
class UserLikes(models.Model):
user = models.ForeignKey(User)
colour = models.ForeignKey(Colour)
thing = models.ForeignKey(Thing)
class Meta:
verbose_name_plural = "User Likes"
def __unicode__(self):
return '%d - %s' % (self.pk, self.user)
在我的觀點:
def ThingPicker(request):
if request.method == 'POST':
form = ThingForm(request.POST)
if form.is_valid():
colour = form.cleaned_data['colour']
thing = form.cleaned_data['thing']
likes = UserLikes(user=request.user, colour=colour, thing=thing)
likes.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('thing_picker.html', {
'form': form,
}, RequestContext(request))
else:
form = ThingForm()
return render_to_response('thing_picker.html', {
'form': form,
}, RequestContext(request))
在我tests.py我想要做這樣的事情這個(EDITED):
class ViewTests(TestCase):
def setUp(self):
self.client = Client()
def test_thingpicker(self):
User.objects.create_superuser('foo', '[email protected]', 'bar')
self.client.login(username='foo', password='bar') # request.user is now user foo
response = self.client.post('/colours/things/', {'colour': 1, 'thing': 2})
userlike = UserLikes.objects.get(pk=1)
self.assertEqual(userlike.colour_id, 1)
我得到一個錯誤:
DoesNotExist: UserLikes matching query does not exist.
如果我與測試客戶端嘗試在外殼:
>>> c = Client()
>>> user1 = User.objects.create_superuser('foo', '[email protected]', 'bar')
>>> c.login(username='foo', password='bar')
>>> c.post('/colours/things/', {'user': user1, 'colour': 1, 'thing': 2})
>>> userlike = UserLikes.objects.get(pk=1)
>>> userlike.colour_id
1L
我得到預期的結果。
感謝。所以我改變了測試代碼,以便對登錄用戶進行測試。我可以用shell中的'Client'來模擬這個,但是測試仍然失敗,說:'DoesNotExist:UserLikes匹配查詢不存在。 –
我相信新創建的UserLikes的PK不是1.您可以編輯視圖的原始文章以顯示正確的代碼嗎?目前有一條斷言與View代碼混合在一起。 我已經編輯了'test_thingpicker'的代碼的最後一行,以獲得您剛創建的用戶狀對象。 –
哦耶 - 看到了錯字。不知道爲什麼'pk'不會在新創建的數據庫上是1?當然,在一個全新的數據庫中,'pk'將永遠是1不是嗎? –