2012-06-14 10 views
5

Djangoアプリケーションをテストするために書いたユニットテストがあります。 1つのテストスイートは特に、setUp()関数に多くのコードを持っています。このコードの目的は、データベースのテストデータを作成することです。 (はい、私は器具について知っていて、この場合は使用しないことを選択しました)。ユニットテストスイートを実行すると、実行される最初のテストは合格しますが、スイートの残りのテストは失敗します。エラーの場所は "self.database_object.save()"であり、原因は "IntegrityError:列名は一意ではありません"と記述されています。だから、私の最高の推測では、Djangoは各テストの後にデータベースを正しく破棄していないということです。Djangoユニットテストデータベースが解体されていませんか?

今日は以前は機能していましたが、私はリファクタリングをしていました。 Djangoが各テストの後にデータベースを適切に分解しない理由についてのアイデアはありますか?

答えて

8

基本クラスに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 database transaction facilities, if available, to speed up the process of resetting the database to a known state at the beginning of each test. A consequence of this, however, is that the effects of transaction commit and rollback cannot be tested by a Django TestCase class. If your test requires testing of such transactional behavior, you should use a Django TransactionTestCase.

TransactionTestCase and TestCase are identical except for the manner in which the database is reset to a known state and the ability for test code to test the effects of commit and rollback. A TransactionTestCase resets the database before the test runs by truncating all tables and reloading initial data. A TransactionTestCase may call commit and rollback and observe the effects of these calls on the database.

A TestCase, on the other hand, does not truncate tables and reload initial data at the beginning of a test. Instead, it encloses the test code in a database transaction that is rolled back at the end of the test. It also prevents the code under test from issuing any commit or rollback operations on the database, to ensure that the rollback at the end of the test restores the database to its initial state. In order to guarantee that all TestCase code starts with a clean database, the Django test runner runs all TestCase tests first, before any other tests (e.g. doctests) that may alter the database without restoring it to its original state.

+0

:ここでは違いがあります。ティショーありがとう! –

関連する問題