2010-05-15 140 views
18

我有一個是給我的錯誤以下Django的測試用例:問題測試

class MyTesting(unittest.TestCase): 
    def setUp(self): 
     self.u1 = User.objects.create(username='user1') 
     self.up1 = UserProfile.objects.create(user=self.u1) 

    def testA(self): 
     ... 

    def testB(self): 
     ... 

當我運行我的測試,testA將成功地通過,但之前testB開始,我得到以下錯誤:

IntegrityError: column username is not unique 

很明顯,這是試圖創建self.u1每個測試用例前,發現它已經存在於數據庫中。如何在每個測試用例之後正確清理它,以便後續案例正確運行?

回答

27

setUptearDown單元測試中的方法在每個測試用例之前和之後被調用。定義tearDown刪除創建的用戶的方法。

class MyTesting(unittest.TestCase): 
    def setUp(self): 
     self.u1 = User.objects.create(username='user1') 
     self.up1 = UserProfile.objects.create(user=self.u1) 

    def testA(self): 
     ... 

    def tearDown(self): 
     self.up1.delete() 
     self.u1.delete() 

我也使用post_save信號,除非你真的想手動創建的用戶配置文件爲每個用戶奉勸create user profiles。在刪除評論

後續

Django docs

When Django deletes an object, it emulates the behavior of the SQL constraint ON DELETE CASCADE -- in other words, any objects which had foreign keys pointing at the object to be deleted will be deleted along with it.

在你的情況下,用戶配置文件指向用戶,所以你應該先刪除該用戶刪除的配置文件同時。

+0

謝謝!我現在遇到的問題是,當我刪除up1時,刪除不會級聯和刪除u1,即使我已將User指定爲UserProfile的外鍵。例如'user = models.ForeignKey(User,unique = True)' – theycallmemorty 2010-05-15 15:00:16

+0

實際上,您應該刪除用戶以一次性級聯和刪除用戶配置文件,或者先刪除用戶配置文件,然後再刪除用戶。 – 2010-05-15 15:04:56

+0

Bah ...我讀的不是在文檔中,但由於某種原因弄糊塗外鍵所指向的方向... – theycallmemorty 2010-05-15 16:09:00

2

準確地說,setUp存在的目的是在每個測試用例之前運行一次。

相反的方法,即各測試用例之後運行一次之一,被命名爲tearDown:這就是你刪除self.u1等(比如通過只調用self.u1.delete(),除非你有另外補充專門的清理要求,只是刪除對象)。

8

如果你想讓django在每次測試運行後自動刷新測試數據庫,那麼你應該擴展django.test.TestCase而不是django.utils.unittest.TestCase(就像你現在正在做的那樣)。

在每次測試後轉儲數據庫是一種很好的做法,所以您可以確保測試是一致的,但請注意,由於此額外開銷,您的測試將運行得更慢。

查看警告部分中的"Writing Tests" Django Docs