Django:测试困惑

标签 django unit-testing

在我编写的单元测试中,我为每个 TestCase 提供了一个测试夹具。但是,当它在测试套件中运行时,我不断重复(IntegrityError)。

所以,我想知道,难道不应该在每个测试用例开始时以及在该测试用例中执行每个测试之后创建和填充数据库,以便我可以为每个测试用例提供不同的固定装置吗?


编辑:添加测试代码

class DashboardTestCase(TestCase):
    fixtures = ['initial.json']

    def setUp(self):
        u = User(username='su')
        u.save()
        self.name = "Test Dashboard"
        self.slug = "test-dashboard"
        self.description = "Test Description"
        self.fiscal_year = "2011"
        self.region = "Test Region"
        self.review_date = "2010-08-01"
        self.date_completed = "2009-03-15"
        self.prepared_by = "Test User"
        self.dashboard = Dashboard(name=self.name, description=self.description, fiscal_year=self.fiscal_year,
                                    region=self.region, review_date=self.review_date, date_completed=self.date_completed,
                                    prepared_by=self.prepared_by)
        self.dashboard.save()

    def testDashboardName(self):
        self.assertEqual(self.dashboard.name, self.name)
    def testDashboardDescription(self):
        self.assertEqual(self.dashboard.description, self.description)
    def testDashboardFiscalYear(self):
        self.assertEqual(self.dashboard.fiscal_year, self.fiscal_year)
    def testDashboardRegion(self):
        self.assertEqual(self.dashboard.region, self.region)
    def testDashboardReviewDate(self):
        self.assertEqual(self.dashboard.review_date, self.review_date)
    def testDashboardDateCompleted(self):
        self.assertEqual(self.dashboard.date_completed, self.date_completed)
    def testDashboardPreparedBy(self):
        self.assertEqual(self.dashboard.prepared_by, self.prepared_by)
    def testDashboardSlug(self):
        self.assertEqual(self.dashboard.slug, self.slug)
    def testDashboardSlugClash(self):
        # Create another dashboard with exactly the same name.
        self.dashboard2 = Dashboard(name='Test Dashboard')
        self.dashboard2.save()
        self.assertEqual(self.dashboard2.slug, 'test-dashboard1')

和回溯:

Installing json fixture 'initial_data' from '/Users/Eric/Documents/DjangoProjects/MMR/../MMR/dashboard/fixtures'.
Problem installing fixture '/Users/Eric/Documents/DjangoProjects/MMR/../MMR/dashboard/fixtures/initial_data.json': Traceback (most recent call last):
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/management/commands/loaddata.py", line 169, in handle
    obj.save(using=using)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/core/serializers/base.py", line 165, in save
    models.Model.save_base(self.object, using=using, raw=True)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/base.py", line 501, in save_base
    rows = manager.using(using).filter(pk=pk_val)._update(values)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/query.py", line 491, in _update
    return query.get_compiler(self.db).execute_sql(None)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 861, in execute_sql
    cursor = super(SQLUpdateCompiler, self).execute_sql(result_type)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 727, in execute_sql
    cursor.execute(sql, params)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/django/db/backends/mysql/base.py", line 86, in execute
    return self.cursor.execute(query, args)
  File "build/bdist.macosx-10.5-i386/egg/MySQLdb/cursors.py", line 174, in execute
    self.errorhandler(self, exc, value)
  File "build/bdist.macosx-10.5-i386/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
IntegrityError: (1062, "Duplicate entry 'dashboard-action' for key 'app_label'")

最佳答案

So, I am wondering, isn't the database supposed to be created and populated at the beginning of each TestCase

数据库 仅在测试运行开始时创建一次。即当你执行./manage.py test时。在执行每个测试方法之前和之后分别加载和删除测试夹具。这意味着在执行每个测试方法之前,所有的固定装置都会加载到数据库中。运行所有测试后删除数据库

I keep getting duplicate (IntegrityError) when it runs in the test suite

在没有看到代码的情况下,我首先要检查的是 initial_data(如果它存在)。 Initial_datasyncdb 结束时加载到数据库中,这发生在测试开始之前。确保您的 initial_data 没有加载任何冲突数据。

第二个要看的地方是其他夹具,尤其是在每个测试类使用多个夹具文件的情况下。

更新

Problem installing fixture '/Users/Eric/Documents/DjangoProjects/MMR/../MMR/dashboard/fixtures/initial_data.json':

似乎错误发生在 甚至在 夹具 (initial.json) 加载之前。 initial_data.json 中很可能存在重复的内容,从而破坏了数据库的完整性。

这就是我进行故障排除的方式:

"Duplicate entry 'dashboard-action' for key 'app_label'"
  1. 确定哪个模型/表具有匹配 app_label
  2. 的约束
  3. 遍历 initial_data.json 并找出是否存在两行具有相同的 app_label 值。
  4. 删除其中一个并重试。

附带说明一下,我建议将测试夹具重命名为其他名称。很容易混淆 initial.jsoninitial_data.json。当然,除非你打算使用 initial_data.json。在这种情况下,fixtures = ... 行是多余的,可以将其删除,因为无论如何都会加载 initial_data.json

更新 2

在沾沾自喜地提出建议并拍拍自己的背后,我想到了这个 Django bug .我正在挖掘更多的污垢。找到更多内容后会再次更新。

关于Django:测试困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3522744/

相关文章:

javascript - 用 Jest 和 sequelize-mock 模拟 Sequelize

c# - 使用 NUnit 和 C# 对异步方法进行单元测试

django - Heroku/Django 部署 : why am I getting an error 500 with successful deploy and static collection?

javascript - 使用 JavaScript 填充 Django 表单

python - Django: 'last_login' 中的未知列 'field list'

python - render_to_response 时 Django View ValueError

c++ - 使用 INSTANTIATE_TEST_CASE_P 的同一 Fixture 的不同实例

unit-testing - junit:相互依赖的测试

python - 将参数传递给 side_effect 函数以在 unittest.mock 中打补丁

python - Django、MySQL、同步数据库 : Access Denied to valid user