2015-10-24 27 views
0

這是我的代碼:Python/Django - 如何讓單元測試類中的所有方法共享相同的數據庫?

鏈接到我的進口在這裏: https://github.com/django/django/blob/master/django/core/urlresolvers.py https://github.com/django/django/blob/master/django/contrib/auth/models.py https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/status.py https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/test.py

from django.core.urlresolvers import reverse 
from django.contrib.auth.models import User 
from rest_framework import status 
from rest_framework.test import APITestCase 

class UserTests(APITestCase): 
    def test_create_user(self): 
     """ 
     Ensure we can create a new user object. 
     """ 
     url = reverse('user-list') 
     data = {'username': 'a', 'password': 'a', 'email': '[email protected]'} 
     # Post the data to the URL to create the object 
     response = self.client.post(url, data, format='json') 
     self.assertEqual(response.status_code, status.HTTP_201_CREATED) 
     # Check the database to see if the object is created. 
     # This check works. 
     self.assertEqual(User.objects.count(), 1) 

    def test_get_user(self): 
     """ 
     Ensure we can get a list of user objects. 
     """ 
     # This fails and returns an error 
     self.assertEqual(User.objects.count(), 1) 

當我運行測試,它提出了一個錯誤,說AssertionError: 0 != 1因爲在功能test_get_user ,在test_create_user中創建的用戶不可見。有沒有辦法讓我在一個班級中的所有方法共享相同的數據庫,所以如果我在test_create_user中創建一個用戶,我可以通過下面的方法訪問它?

編輯:我希望他們共享相同的數據庫的所有方法的原因是因爲我所有在UserTests類中的測試用例都需要創建一個用戶,所以我不想重複相同的代碼全部即使在test_create_user中進行測試時也是如此。

我知道我可以使用def setUp(self)但我在我的第一個方法中進行「創建用戶」測試,因此我希望能夠測試是否可以在def setUp(self)中創建它之前先創建它。

+0

請添加'APITestCase'和您的導入。 –

+0

我認爲爲單元測試用戶創建單獨的測試用例更容易。它基本上會測試用於創建用戶的代碼,這些用戶可用於在其他測試用例中預填充數據庫。 – Ivan

+0

@SebastianWozny我添加了GitHub源代碼的鏈接(這是默認的Django和DRF源代碼)。 – user2719875

回答

4

您應該在每個測試中明確設置您的數據。測試不能相互依賴。

+0

在我的情況下(請參閱我的文章底部的編輯),您是否仍然建議反覆使用我所有方法中的同一部分代碼(我創建用戶的部分)?還是有更好的方法來做到這一點?注意:我不想在'def setUp(self)'中創建用戶,因爲我希望能夠測試是否可以在創建用戶之前先創建一個用戶(測試在第一個方法中完成 - 'def test_create_user (self)' – user2719875

+0

不,你可以直接通過ORM創建對象;如果你沒有專門測試,不需要通過帖子,但是如果你願意,你可以把它放到一個單獨的實用工具中。 –