我正在尝试使用测试运行程序测试 Django 应用程序。我想设置一次测试数据以运行多个不同的测试类,而不是在每个测试类中设置相同的数据。因此,我使用 setUpTestData()
而不是 setUp()
。该模型包含一个ManyToManyField
,用于将协作者连接到文章。当我使用 setUpTestData()
设置一个类来测试模型时,我能够从 Collaborator
模型和 Article
保存和检索对象> 模型。
但是,当我尝试保存多对多关系时,出现该表不存在的错误。如何设置测试以便可以重用这些数据,包括多对多关系。
这是我的代码:
from django.test import TestCase
from cv.settings import PUBLICATION_STATUS, STUDENT_LEVELS
from cv.models import Article, ArticleAuthorship, Collaborator
from tests.cvtest_data import PublicationTestCase
class ArticleTestCase(TestCase):
"""
Run tests of Django-CV :class:`~cv.models.Article` model.
"""
@classmethod
def setUpTestData(cls):
# Collaborator
cls.col_einstein = Collaborator.objects.create(
first_name="Albert", last_name="Einstein", email="ae@example.edu"
)
# Article
cls.art_gravitation = Article.objects.create(
title='On the Generalized Theory of Gravitation', short_title='Generalized Theory of Gravitation',
slug='gen-theory-gravitation', pub_date='1950-04-01',
status=PUBLICATION_STATUS['PUBLISHED_STATUS']
)
# Authorship: ManyToManyField
cls.auth = ArticleAuthorship(
article=cls.art_gravitation,
collaborator=cls.col_einstein,
display_order=1
)
cls.auth.save()
def test_article_string(self):
"""Test that model returns short title of article as string"""
a = Article.objects.get(
short_title="Generalized Theory of Gravitation")
self.assertEqual(a.__str__(), "Generalized Theory of Gravitation")
我得到的错误是:
======================================================================
ERROR: test suite for <class 'tests.test_article2.ArticleTestCase'>
----------------------------------------------------------------------
Traceback (most recent call last):
File "~/webdev/djangoapps/django-vitae/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "~/webdev/djangoapps/django-vitae/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 296, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: main.cv_article__old
我尝试添加 super(ArticleTestCase, cls).setUpTestData()
并在测试函数中创建关系,但似乎不应该使用 setUpTestData()
>。但我做了一个实验,它引发了同样的错误。
最佳答案
我发现问题不在于我的测试,而是旧版本的 Django 回滚数据库事务的方式与 SQLite 的更新行为之间不兼容,如 this bug report 中所述。 (我使用的是旧代码,想在更新到新版本之前运行测试)。将 Django 更新到版本 2.1.5 解决了该错误。
关于python - Django SetUpTestData 导致 ManyToManyField 数据库错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59459482/