2016-11-21 74 views
0

我創建了Django的admin.py一個自定義功能和即時通訊試圖測試使用範圍:覆蓋測試Django管理自定義函數

class Responsible(admin.ModelAdmin): 

    """ 
    Inherits of admin class 
    """ 

    list_display = ('user', 'Name', 'last_name', 'process',) 
    search_fields = ('p__name', 'user__username') 

    def User_Name(self, obj): 
     return obj.user.first_name 

    def User_Last_Name(self, obj): 
     return obj.user.last_name 

負責模型有一個Django用戶模型外鍵......到目前爲止,我嘗試了很多方法來測試:

class AdminTestCase(TestCase): 

    fixtures = ["initial_data.json"] 


    def test_first_name(self): 
     rsf = Responsible.objects.get(id = 1) 
     User_Name(rsf) 

    def test_first_name2(self): 
     self.obj = Responsible.objects.get(id = 1) 

但沒有什麼作品....請任何幫助嗎?

在此先感謝!

回答

0

其實我發現了它,並且它是,如果有人在任何時候需要它相當簡單:

def test_first_name_admin(self): 
    rsf = ResponsibleStateFlow.objects.get(id = 1) 
    ResponsibleStateFlowAdmin.User_Name(self, rsf) 
    ResponsibleStateFlowAdmin.User_Last_Name(self, rsf) 
1

你將不得不在django admin中使用django客戶端和Responsible模型的打開列表頁面。

https://docs.djangoproject.com/en/1.10/topics/testing/tools/#overview-and-a-quick-example

通過打開管理員列表頁面自定義函數將被調用,因此將在測試範圍內。

所以基本上類似下面需要做的事情:

from django.test import Client, TestCase 

class BaseTestCase(TestCase): 
    """Base TestCase with utilites to create user and login client.""" 

    def setUp(self): 
     """Class setup.""" 
     self.client = Client() 
     self.index_url = '/' 
     self.login() 

    def create_user(self): 
     """Create user and returns username, password tuple.""" 
     username, password = 'admin', 'test' 
     user = User.objects.get_or_create(
      username=username, 
      email='[email protected]', 
      is_superuser=True 
     )[0] 
     user.set_password(password) 
     user.save() 
     self.user = user 
     return (username, password) 

    def login(self): 
     """Log in client session.""" 
     username, password = self.create_user() 
     self.client.login(username=username, password=password) 


class AdminTestCase(BaseTestCase): 

    def test_responsible_list(self): 
     response = self.client.get('/admin/responsilbe_list/') 
     # assertions.... 
+0

謝謝您的回答,從來沒有做過那...你能否給我一個例子來解釋第一個叫做「User_Name」的函數? – jsanchezs

+0

已更新的答案。 – falloutcoder

+0

我很感謝你的幫助,但我認爲這不完全是我需要的,我已經測試過登錄和註銷......我需要的是測試我發佈的那些函數 – jsanchezs