【发布时间】:2019-01-30 17:13:26
【问题描述】:
我正在使用 Django 和 Python 3.7。我想在运行测试之前加载一些测试数据。我认为在我的测试中指定一个“fixtures”元素会做到这一点,但它似乎没有被加载。我用这个内容创建了文件 mainpage/fixtures/test_data.yaml
model: mainpage.website
pk: 1
fields:
path: /testsite
model: mainpage.article
pk: 1
fields:
website: 1
title: 'mytitle'
path: '/test-path'
url: 'http://www.mdxomein.com/path'
created_on:
type: datetime
columnDefinition: TIMESTAMP DEFAULT CURRENT_TIMESTAMP
model: mainpage.articlestat:
pk: 1
fields:
article: 1
elapsed_time_in_seconds: 300
hits: 2
我在下面的测试文件中指定了夹具...
from django.test import TestCase
from mainpage.models import ArticleStat, Article
import unittest
class TestModels(unittest.TestCase):
fixtures = ['/mainpage/fixtures/test_data.yaml',]
# Test saving an article stat that hasn't previously
# existed
def test_add_articlestat(self):
id = 1
article = Article.objects.filter(id=id)
self.assertTrue(article, "A pre-condition of this test is that an article exist with id=" + str(id))
articlestat = ArticleStat(article=article,elapsed_time_in_seconds=250,votes=25,comments=15)
articlestat.save()
article_stat = ArticleStat.objects.get(article=article)
self.assertTrue(article_stat, "Failed to svae article stat properly.")
但是运行我的测试时,似乎没有加载任何测试数据...
(venv) localhost:mainpage_project davea$ cd /Users/davea/Documents/workspace/mainpage_project; source ./venv/bin/activate; python manage.py test
test activated!
Creating test database for alias 'default'...
/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/db/models/fields/__init__.py:1421: RuntimeWarning: DateTimeField Article.front_page_first_appeared_date received a naive datetime (2019-01-30 17:02:31.329751) while time zone support is active.
RuntimeWarning)
System check identified no issues (0 silenced).
F
======================================================================
FAIL: test_add_articlestat (mainpage.tests.TestModels)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/davea/Documents/workspace/mainpage_project/mainpage/tests.py", line 15, in test_add_articlestat
self.assertTrue(article, "A pre-condition of this test is that an article exist with id=" + str(id))
AssertionError: <QuerySet []> is not true : A pre-condition of this test is that an article exist with id=1
----------------------------------------------------------------------
Ran 1 test in 0.001s
我尝试将文件名更改为根本不存在的文件名,以查看是否出现不同的错误,但没有。所以我认为这个“Fixtures”约定根本不起作用。如何在运行测试之前加载测试数据?
【问题讨论】:
-
我不相信这是问题所在,因为您应该得到一个缺少夹具的异常,但是您可以尝试将其更改为
fixtures = ['test_data.yaml']吗? Django 应该自动为其添加前缀以在应用程序中使用fixtures目录。
标签: python django python-3.x unit-testing fixtures