测试之间的Django数据

2024-10-16 17:26:38 发布

您现在位置:Python中文网/ 问答频道 /正文

django测试成功后删除数据是否正常?我不是说每次测试运行,让我举个例子:

class MyFooTest(TestCase):
    def test_foo1(self):
        # Some foo test code here

    def test_foo2(self):
        # Some foo test code here

在测试test_foo1期间生成的数据在测试test_foo2时不存在,发生这种情况是否正常?在


Tags: 数据djangotestselfherefoodefcode
1条回答
网友
1楼 · 发布于 2024-10-16 17:26:38

documentation开始,底部部分解释了TransactionTestCase和{}之间的区别:

A TestCase, on the other hand, does not truncate tables after a test. Instead, it encloses the test code in a database transaction that is rolled back at the end of the test. This guarantees that the rollback at the end of the test restores the database to its initial state.

由于每个单独的测试方法都被包装在一个atomic块中,并且每个原子块在测试方法结束时被回滚,这是预期的行为。Django这样做是为了确保测试是孤立的,这样在出现问题时更容易发现问题。在

如果需要在多个测试方法中持久化数据,可以在^{}中创建它们。只需确保不要更改setUpTestData()创建的内存中对象。内存中的更改将持续,但数据库更改将回滚。在

相关问题 更多 >