Django SetUpTestData导致多个字段出现数据库错误

2024-09-25 10:26:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用测试运行程序测试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()。但我只是做了个实验,结果也犯了同样的错误


Tags: ofdjangofrom模型testimporttitlearticle
1条回答
网友
1楼 · 发布于 2024-09-25 10:26:57

我发现问题不在于我的测试,而是Django的旧版本回滚数据库事务的方式与SQLite的更新行为之间的不兼容,如this bug report中所述(我使用的是旧代码,希望在更新到新版本之前运行测试)。将Django更新到2.1.5版解决了这个错误

相关问题 更多 >