2014-10-31 94 views
3
class MyClassTest(TestCase): 
    def setUp(self): 
     Someclass.objects.create() 

    def test_first_test(self): 
     # Here, Someclass.objects.all()[0].pk -> returns 1 

    def test_second_test(self): 
     # Here, Someclass.objects.all()[0].pk -> returns 2 !!! (bad !) 

使用SetUp()方法,應該在每次測試之間清除並重新創建數據。 那麼,爲什麼ids會從一個測試增加到另一個?這對我來說並不明顯。爲什麼在Django的測試中對象主鍵增加?

這樣我就不能做基於ID的測試(因爲它們取決於其他測試)。 這就是爲什麼我總想得到1的結果。

請注意,我對數據本身沒有任何問題,舊數據很好地從一個測試清除到另一個測試。問題只是關於IDS。

我在這裏讀到django object ids increment between unit tests問題是關係到數據庫,而不是Django,但Django中有沒有什麼竅門可以改變它?

回答

2

您很可能會清除數據,包括數據庫中的數據。這與重新創建數據庫或重新創建序列不同。如果序列仍然存在,它們會在他們離開的地方繼續。

+0

我不知道理解。我沒有自己清理數據,Django在每次測試之間爲我做了這些。數據實際上已被清除,問題僅與ID有關。 – 2014-10-31 00:32:01

+1

除非您使用固定裝置(它會覆蓋特定的ID),否則可能會刪除這些值,但數據庫仍可能使用連續的ID。 – monkut 2014-10-31 00:36:11

2

有測試文檔中警告:

https://docs.djangoproject.com/en/dev/topics/testing/overview/

警告:如果您的測試依賴於數據庫訪問,如創建或 查詢模式,一定要創建您的測試類的 子django.test.TestCase而不是unittest.TestCase。

使用避免unittest.TestCase生成運行在 交易的每項測試,刷新數據庫的成本,但如果你的測試與 數據庫交互他們的行爲會根據該測試 亞軍執行的順序而定。這可能導致單元測試在隔離運行 時通過,但在套件中運行時失敗。

您使用的是django.test.TestCaseunittest.TestCase

如果你需要保持PK integrety它似乎有一個選項,您可以嘗試:

https://docs.djangoproject.com/en/dev/topics/testing/advanced/#django.test.TransactionTestCase.reset_sequences

在TransactionTestCase設置reset_sequences = True將確保序列在試運行之前始終處於復位狀態:

class TestsThatDependsOnPrimaryKeySequences(TransactionTestCase): 
    reset_sequences = True 

    def test_animal_pk(self): 
     lion = Animal.objects.create(name="lion", sound="roar") 
     # lion.pk is guaranteed to always be 1 
     self.assertEqual(lion.pk, 1) 

因爲,django.test.LiveServerTestCase似乎是子類TransactionTestCase這可能應該適合你。

+0

我使用django.test.LiveServerTestCase(我猜它django.test.TestCase繼承) – 2014-10-31 00:29:57

-1

,這也可能爲你工作

class MyClassTest(TestCase): 
    @classmethod 
    def setUpTestData(cls): 
     cls.x = Someclass() 
     cls.x.save() 

    def test_first_test(self): 
     # Here, Someclass.objects.all()[0].pk -> returns 1 

    def test_second_test(self): 
     # Here, Someclass.objects.all()[0].pk -> returns 1 !!! (good !) 
     # Here, self.x.pk -> returns 1 !!! (good !) 
相關問題