递归单元测试发现 [英] Recursive unittest discover
问题描述
我有一个包含tests"目录的包,我在其中存储了我的单元测试.我的包裹看起来像:
<预><代码>.├── 执照├── 模型│ └── __init__.py├── README.md├──需求.txt├── tc.py├── 测试│ ├── db│ │ └── test_employee.py│ └── test_tc.py└── 待办事项.txt从我的包目录中,我希望能够找到 tests/test_tc.py
和 tests/db/test_employee.py
.我不想安装第三方库(nose
等),也不想手动构建 TestSuite
来运行它.
当然有办法告诉 unittestdiscover
在找到测试后不要停止查找吗?python -m unittest discover -s tests
会找到 tests/test_tc.py
而 python -m unittest discover -s tests/db
会找到 tests/test_tc.py
代码>tests/db/test_employee.py.没有办法同时找到吗?
在做一些挖掘时,似乎只要更深的模块仍然可导入,它们就会通过 python -m unittest discover<被发现/代码>.那么,解决方案是简单地向每个目录添加一个
__init__.py
文件以将它们打包.
只要每个目录都有一个__init__.py
,python -m unittestdiscover
就可以导入相关的test_*
模块.>
I have a package with a directory "tests" in which I'm storing my unit tests. My package looks like:
.
├── LICENSE
├── models
│ └── __init__.py
├── README.md
├── requirements.txt
├── tc.py
├── tests
│ ├── db
│ │ └── test_employee.py
│ └── test_tc.py
└── todo.txt
From my package directory, I want to be able to find both tests/test_tc.py
and tests/db/test_employee.py
. I'd prefer not to have to install a third-party library (nose
or etc) or have to manually build a TestSuite
to run this in.
Surely there's a way to tell unittest discover
not to stop looking once it's found a test? python -m unittest discover -s tests
will find tests/test_tc.py
and python -m unittest discover -s tests/db
will find tests/db/test_employee.py
. Isn't there a way to find both?
In doing a bit of digging, it seems that as long as deeper modules remain importable, they'll be discovered via python -m unittest discover
. The solution, then, was simply to add a __init__.py
file to each directory to make them packages.
.
├── LICENSE
├── models
│ └── __init__.py
├── README.md
├── requirements.txt
├── tc.py
├── tests
│ ├── db
│ │ ├── __init__.py # NEW
│ │ └── test_employee.py
│ ├── __init__.py # NEW
│ └── test_tc.py
└── todo.txt
So long as each directory has an __init__.py
, python -m unittest discover
can import the relevant test_*
module.
这篇关于递归单元测试发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!