gpt4 book ai didi

python - Django 单元测试数据库没有被拆除?

转载 作者:太空狗 更新时间:2023-10-29 22:23:23 25 4
gpt4 key购买 nike

我编写了一些单元测试来测试我的 Django 应用程序。特别是一个测试套件在其 setUp() 函数中有很多代码。所述代码的目的是为数据库创建测试数据。 (是的,我知道固定装置并且在这种情况下选择不使用它们)。当我运行单元测试套件时,运行的第一个测试通过,但随后套件中的其余测试失败。所有失败的消息都是相同的:它提到错误的位置是“self.database_object.save()”,原因是“IntegrityError:列名不唯一”。所以,我最好的猜测是 Django 没有在每次测试后正确地拆除数据库。

今天早些时候它可以正常工作,但我猜我做的一些重构搞砸了它。关于为什么每次测试后 Django 都没有正确拆除数据库有什么想法吗?

最佳答案

你的基类使用 TestCase 还是 TransactionTestCase?有时,此行为与 Django 为 TestCase 进行的有利于 TransactionTestCase 的优化有关。这是区别:

https://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs#django.test.TransactionTestCase

class TransactionTestCase

Django TestCase classes make use of databasetransaction facilities, if available, to speed up the process ofresetting the database to a known state at the beginning of each test.A consequence of this, however, is that the effects of transactioncommit and rollback cannot be tested by a Django TestCase class. Ifyour test requires testing of such transactional behavior, you shoulduse a Django TransactionTestCase.

TransactionTestCase and TestCase are identical except for the mannerin which the database is reset to a known state and the ability fortest code to test the effects of commit and rollback. ATransactionTestCase resets the database before the test runs bytruncating all tables and reloading initial data. ATransactionTestCase may call commit and rollback and observe theeffects of these calls on the database.

A TestCase, on the other hand, does not truncate tables and reloadinitial data at the beginning of a test. Instead, it encloses the testcode in a database transaction that is rolled back at the end of thetest. It also prevents the code under test from issuing any commit orrollback operations on the database, to ensure that the rollback atthe end of the test restores the database to its initial state. Inorder to guarantee that all TestCase code starts with a cleandatabase, the Django test runner runs all TestCase tests first, beforeany other tests (e.g. doctests) that may alter the database withoutrestoring it to its original state.

关于python - Django 单元测试数据库没有被拆除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11040557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com