【问题标题】:How do I load my test yaml file prior to running my Django test?如何在运行 Django 测试之前加载我的测试 yaml 文件?
【发布时间】: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


【解决方案1】:

为了以这种方式使用fixture,需要设置TransactionTestCase.fixtures1

加载固定装置的魔法发生在TransactionTestCase。这使得子类 TransactionTestCase 的测试类例如django.test.TestCase 还加载在fixtures 属性中指定的fixtures。 2

当前的TestModels 测试类是unitest.TestCase 的子类,因此对fixture 设置没有任何作用。 3

from django.test import TestCase

class TestModels(TestCase):
    fixtures = ['test_data.yaml',]

通常设置夹具文件的名称而不是夹具文件的整个路径就可以了。 如果您需要为要在其中发现的灯具设置自定义文件夹,可以通过设置 FIXTURE_DIRS 4

来指定

【讨论】:

    【解决方案2】:

    您应该(如@OluwafemiSule)在他的回答中使用django.test.TestCase 声明,以便考虑到类属性fixtures

    您能否使用unittest.TestCase 实现您的测试和加载夹具?

    虽然不建议您像这样在 setUp 方法中以编程方式加载固定装置:

    from django.core.management import call_command
    
    def setUp(self): 
       call_command('loaddata', 'initial_data.yml', app_label='myapp')
    

    但是如果您在后续测试中使用它,这种方法将要求您回滚对加载的数据所做的任何更改。

    正确的方法

    您可以从Fixtures in Unit Tests 部分中的 Django 测试文档中阅读:

    Django 测试用例在固定装置方面为您做的最重要的事情是 它为您的所有测试保持一致的状态。在运行每个测试之前,数据库都会被刷新:将其返回到原始状态(就像在您的第一个 syncdb 之后)。然后你的夹具被加载到数据库中,然后调用 setUp(),然后运行你的测试,然后调用 tearDown()。 当您尝试制作一个好的测试套件时,让您的测试相互隔离非常重要

    这就是为什么你应该使用django.test.TestCase

    你的灯具好吗?

    另一个重要提示是,您可以使用命令testserver 来查看您的灯具是否良好:

    $ django-admin testserver mydata.json
    

    这将使用来自给定夹具的数据运行 Django 开发服务器(如在 runserver 中)。你可以阅读testserver 命令,你会发现这是一个非常有用的工具。

    【讨论】:

      猜你喜欢
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-03
      • 2016-11-27
      • 2023-04-11
      • 2015-02-21
      • 1970-01-01
      相关资源
      最近更新 更多