对于Django单元测试,为什么有些测试运行程序会考虑到生产数据库,而另一些则没有呢?

2024-05-16 23:07:14 发布

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

在启动django tutorial应用程序的过程中,我注意到某些测试运行人员在运行单元测试时正在访问生产数据库,而其他测试运行人员似乎忽略了这一点。在

我用三个测试将django应用程序精简为最基本的功能:

  • 模型实例化(对照试验)
  • 对空数据库的请求
  • 对只有一个元素的数据库的请求

我向生产数据库添加了一个元素,并在eclipsepydev使用的测试运行程序中运行它们。在

代码在my GitHub site上可用。在

django测试运行程序通过了(声称正在创建一个测试数据库?)公司名称:

(django)kenners@elendil:~/my_first_app$ python manage.py test demo
Creating test database for alias 'default'...
...
----------------------------------------------------------------------
Ran 3 tests in 0.135s

OK
Destroying test database for alias 'default'...

pytest运行程序通过(没有任何此类声明,尽管它可能被隐藏):

^{pr2}$

鼻梁失败(它将生产数据库与测试相结合):

(django)kenners@elendil:~/my_first_app$ python -m nose demo/tests.py
FF.
======================================================================
FAIL: test_no_available_things (demo.tests.DemoDatabaseTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/kenners/my_first_app/demo/tests.py", line 23, in test_no_available_things
    self.assertEquals(0, pull_count_from_body(response))
AssertionError: 0 != 1

======================================================================
FAIL: test_one_available_things (demo.tests.DemoDatabaseTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/kenners/my_first_app/demo/tests.py", line 30, in test_one_available_things
    self.assertEquals(1, pull_count_from_body(response))
AssertionError: 1 != 2

----------------------------------------------------------------------
Ran 3 tests in 0.334s

FAILED (failures=2)

unittest2运行程序失败(原因相同):

(django)kenners@elendil:~/my_first_app$ python -m unittest2 demo.tests
FF.
======================================================================
FAIL: test_no_available_things (demo.tests.DemoDatabaseTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "demo/tests.py", line 23, in test_no_available_things
    self.assertEquals(0, pull_count_from_body(response))
AssertionError: 0 != 1

======================================================================
FAIL: test_one_available_things (demo.tests.DemoDatabaseTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "demo/tests.py", line 30, in test_one_available_things
    self.assertEquals(1, pull_count_from_body(response))
AssertionError: 1 != 2

----------------------------------------------------------------------
Ran 3 tests in 0.348s

FAILED (failures=2)

nose/unittest2的哪个部分导致这些测试失败?为什么pytest有效?在


Tags: djangoinpytest程序数据库appdemo
1条回答
网友
1楼 · 发布于 2024-05-16 23:07:14

在运行单元测试时触摸生产数据库是绝对不合适的。 单元测试通常应该在模拟数据库上工作。集成测试should work on a real,但测试数据库。 但是生产数据库呢?你为什么要冒真实数据的风险?在

Django documentation声明“测试运行程序负责创建自己的测试数据库”。在

django-nose documentation中可以清楚地看到它应该在测试数据库上运行测试。在

相关问题 更多 >