2012-10-23 41 views
0

我有一個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 

我得到預期的結果。

回答

1

有一些奇怪的與您的視圖代碼(偶然的剪切和粘貼?),但是從下面的代碼行:

likes = UserLikes(user=request.user, colour=colour, thing=thing) 

我猜你得到登錄用戶的電流。從您的測試案例正確地得到您的新創建的超級用戶,你應該這樣做:

def test_thingpicker(self): 
    user1 = User.objects.create_user('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(user=user1, color=1, thing=2) 

此外,還應該注意的是request.user可能是一個AnonymousUser(見https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.AnonymousUser),因此,你應該檢查是否有用戶在創建UserLikes之前登錄。

您可以通過使用@login_required裝飾(https://docs.djangoproject.com/en/dev/topics/auth/#the-login-required-decorator)或手動檢查request.user.is_authenticated()https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.AbstractBaseUser.is_anonymous)這樣做。

爲什麼UserLikes未創建

從視圖:

colour = form.cleaned_data['colour'] 
thing = form.cleaned_data['thing'] 
likes = UserLikes(user=request.user, colour=colour, thing=thing) 

注意,對於UserLikes模型定義的ForeignKey使用彩色和事情。我猜測colourthing的格式是IntegerField,所以你需要檢索實際的Color和Thing對象。

color = Colour.objects.get(pk=form.cleaned_data['colour']) 
thing = Thing.objects.get(pk=form.cleaned_data['thing']) 
likes = UserLikes(user=request.user, colour=colour, thing=thing) 

當然,你需要確保顏色和Thing對象已經被創建之前。

+0

感謝。所以我改變了測試代碼,以便對登錄用戶進行測試。我可以用shell中的'Client'來模擬這個,但是測試仍然失敗,說:'DoesNotExist:UserLikes匹配查詢不存在。 –

+0

我相信新創建的UserLikes的PK不是1.您可以編輯視圖的原始文章以顯示正確的代碼嗎?目前有一條斷言與View代碼混合在一起。 我已經編輯了'test_thingpicker'的代碼的最後一行,以獲得您剛創建的用戶狀對象。 –

+1

哦耶 - 看到了錯字。不知道爲什麼'pk'不會在新創建的數據庫上是1?當然,在一個全新的數據庫中,'pk'將永遠是1不是嗎? –

0

其工作的最終代碼:

tests.py:

class ViewTests(TestCase): 
    """ 
    Run before each test in class 
    """ 
    def setUp(self): 
     self.client = Client() 
     self.user = User.objects.create_superuser(
      'foo', 
      '[email protected]', 
      'pass' 
     ) 
     self.colour = Colour.objects.create(colour='Green') 
     self.thing = Thing.objects.create(
      name='Leaf', 
      colour=self.colour, 
      description='leafy' 
     ) 
     self.logged_in = self.client.login(
      username='foo', 
      password='pass' 
     ) 

    """ 
    Test whether user can login and post choice 
    to db and then check if data can be retreived. 
    """ 
    def test_thingpicker(self): 
     # check new User object created 
     self.assertEqual(User.objects.count(), 1) 
     # check use is logged in 
     self.assertEqual(self.logged_in, True) # check login success 

     # post some data 
     response = self.client.post(
      '/colours/things/', { 
      'colour': self.colour.pk, 
      'thing': self.thing.pk 
      }) 
     self.assertEqual(response.status_code, 200) 

     # check object 
     self.assertEqual(UserLikes.objects.count(), 1) 
     userlikes = UserLikes.objects.get(
      user=self.user, 
      colour_id=self.colour.pk, 
      thing=self.thing.pk 
     ) 
     self.assertEqual(userlikes.colour_id, self.colour.pk) 
相關問題