我正在为我的 Django 应用程序设置一个目录结构,以将功能测试和单元测试分开。我使用 nose 作为我的 Django 项目的测试运行器。
在 Django 项目的根目录下,我有一个名为“tests”的文件夹,其结构如下:
tests
├── __init__.py
├── functional
│ ├── __init__.py
└── unit
├── __init__.py
├── data.py
├── tests.py
如果我只想运行单元测试,我是否应该无法使用项目根目录中的以下内容:
$ nosetests tests.unit
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
如您所见,这不会在 tests.py 文件中找到测试。
但是,当我使用目录结构运行时,发现测试应该是这样的:
$ nosetests tests/unit/
E
# .. Some errors I expected because settings are not initialized when called this way
-----------------
Ran 1 test in 0.001s
FAILED (errors=1)
我错过了什么?我的主要问题是我在 tests.unit.__init__.py 中有一个 setup 函数,应该调用它来为即将进行的测试在测试数据库中创建数据。
谢谢
请您参考如下方法:
这完全取决于tests/unit/__init__.py中的代码类型
当你说
nosetests tests.unit
您指向的是 unit/__init__.py 而不是目录 unit/ 因此如果您的 __init__.py 模块中没有测试那么什么都不会运行。因此,当您说您使用了目录路径然后您的测试开始工作时,这是可以理解的。
你提到
What am I missing? My main issue is that I have a setup function in tests.unit.init.py that should be called for creating the data in the test DB for the upcoming tests.
很可能虽然您在 __init__.py 中有一个设置函数,但您可能从未将您的测试函数导入到 __init__.py
一个快速解决方法是在 __init__.py
from tests.unit.tests import *
也就是说,将任何代码放在 __init__.py 中确实不是很明智,如果您有返回某种配置数据的代码,我建议您创建一个新的库模块将配置数据返回给测试的函数
