如何在 运行 我的 Django 测试之前加载我的测试 yaml 文件?
How do I load my test yaml file prior to running my Django test?
我正在使用 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" 约定根本不起作用。如何在 运行 测试之前加载我的测试数据?
为了以这种方式使用灯具,需要设置 TransactionTestCase.fixtures
。
1
加载固定装置的魔法发生在 TransactionTestCase
中。这是为了让 Test classes that subclasses TransactionTestCase
例如django.test.TestCase
还加载 fixtures 属性中指定的 fixtures。
2
当前 TestModels
测试 class subclasses unitest.TestCase
因此对灯具设置没有任何影响。 3
from django.test import TestCase
class TestModels(TestCase):
fixtures = ['test_data.yaml',]
通常设置夹具文件的名称而不是夹具文件的完整路径就可以了。
如果您需要为要在其中发现的灯具设置自定义文件夹,可以通过设置 FIXTURE_DIRS
4
来指定
您应该(如@OluwafemiSule)在他的回答中使用 django.test.TestCase
声明,以便考虑 class 属性 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 测试文档,您可以阅读:
The big thing that the Django Testcase does for you in regards to fixtures is that it maintains a consistent state for all of your tests. Before each test is run, the database is flushed: returning it to a pristine state (like after your first syncdb). Then your fixture gets loaded into the DB, then setUp() is called, then your test is run, then tearDown() is called. Keeping your tests insulated from each other is incredibly important when you are trying to make a good test suite.
这就是为什么您应该使用 django.test.TestCase
。
你的灯具还好吗?
另一个重要提示是,您可以使用命令 testserver 来查看您的灯具是否良好:
$ django-admin testserver mydata.json
这将使用来自给定固定装置的数据运行 Django 开发服务器(如在 runserver 中)。您可以阅读 testserver 命令,您会发现这是一个非常有用的工具。
我正在使用 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" 约定根本不起作用。如何在 运行 测试之前加载我的测试数据?
为了以这种方式使用灯具,需要设置 TransactionTestCase.fixtures
。
1
加载固定装置的魔法发生在 TransactionTestCase
中。这是为了让 Test classes that subclasses TransactionTestCase
例如django.test.TestCase
还加载 fixtures 属性中指定的 fixtures。
2
当前 TestModels
测试 class subclasses unitest.TestCase
因此对灯具设置没有任何影响。 3
from django.test import TestCase
class TestModels(TestCase):
fixtures = ['test_data.yaml',]
通常设置夹具文件的名称而不是夹具文件的完整路径就可以了。
如果您需要为要在其中发现的灯具设置自定义文件夹,可以通过设置 FIXTURE_DIRS
4
您应该(如@OluwafemiSule)在他的回答中使用 django.test.TestCase
声明,以便考虑 class 属性 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 测试文档,您可以阅读:
The big thing that the Django Testcase does for you in regards to fixtures is that it maintains a consistent state for all of your tests. Before each test is run, the database is flushed: returning it to a pristine state (like after your first syncdb). Then your fixture gets loaded into the DB, then setUp() is called, then your test is run, then tearDown() is called. Keeping your tests insulated from each other is incredibly important when you are trying to make a good test suite.
这就是为什么您应该使用 django.test.TestCase
。
你的灯具还好吗?
另一个重要提示是,您可以使用命令 testserver 来查看您的灯具是否良好:
$ django-admin testserver mydata.json
这将使用来自给定固定装置的数据运行 Django 开发服务器(如在 runserver 中)。您可以阅读 testserver 命令,您会发现这是一个非常有用的工具。