【发布时间】:2019-12-23 17:59:02
【问题描述】:
我正在尝试使用测试运行程序测试 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()。但我把它作为一个实验,它抛出了同样的错误。
【问题讨论】:
-
您使用哪个命令来运行测试?
-
run_testsfromdjango.test.utils.get_runner在包含coverage报告的 runtests.py 文件中
标签: python django unit-testing