2012-06-14 33 views
5

Tôi có một số bài kiểm tra đơn vị tôi đã viết để kiểm tra ứng dụng Django của mình. Một bộ thử nghiệm đặc biệt có rất nhiều mã trong hàm setUp() của nó. Mục đích của mã nói là tạo dữ liệu thử nghiệm cho cơ sở dữ liệu. (Có, tôi biết về đồ đạc và đã chọn không sử dụng chúng trong trường hợp này). Khi tôi chạy bộ kiểm tra đơn vị kiểm tra đầu tiên chạy qua, nhưng sau đó phần còn lại của các thử nghiệm trong bộ phần mềm thất bại. Thông báo cho tất cả các lỗi là như nhau: nó đề cập rằng vị trí của lỗi là "self.database_object.save()" và nguyên nhân là "IntegrityError: tên cột không phải là duy nhất". Vì vậy, tôi đoán tốt nhất là Django không rách cơ sở dữ liệu đúng sau mỗi lần kiểm tra.Cơ sở dữ liệu thử nghiệm đơn vị Django không bị rách?

Trước đó ngày hôm nay nó đã hoạt động, nhưng tôi đoán một số refactoring tôi đã làm sai nó lên. Bất kỳ ý tưởng về lý do tại sao Django không đúng cách rách xuống cơ sở dữ liệu sau mỗi bài kiểm tra?

Trả lời

8

Bạn có sử dụng TestCase hoặc TransactionTestCase cho lớp cơ sở của mình không? Đôi khi hành vi này có liên quan đến việc tối ưu hóa Django làm cho TestCase ủng hộ TransactionTestCase. Đây là sự khác biệt:

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

Đó là vị trí trên. Cảm ơn bạn rất nhiều Tisho! –

Các vấn đề liên quan