您没有提及您使用的是什么单元测试框架,但如果您使用的是pytest,它已经支持the tests are outside the application code 所在的那种应用/测试组织。
setup.py
mypkg/
__init__.py
app.py
view.py
tests/
test_app.py
test_view.py
...
- ..
- 如果您没有
setup.py 文件并且依赖于以下事实
Python默认将当前目录放在sys.path中导入
你的包,你可以执行python -m pytest 来执行测试
直接针对本地副本,不使用pip。
您的代码结构已经正确。您无需手动设置sys.path。您可以正常使用from app import main(请参阅下面的示例test_one.py)。我唯一要添加的是 pytest.ini 来指定测试文件的测试路径和模式。
目录结构:
Project
├── pytest.ini
├── app
│ ├── __init__.py
│ └── main.py
│
├── tests
│ ├── __init__.py
│ └── test_one.py
pytest.ini:
[pytest]
addopts = -v
console_output_style = count
python_files = test_*.py
testpaths = tests
示例main.py:
def calculate(x, y):
return x + y
示例test_one.py:
from app import main
def test_calculate():
assert(3 == main.calculate(1, 2))
运行 pytest:
$ pytest tests
=============================================================================== test session starts ===============================================================================
platform linux -- Python 3.7.2, pytest-4.6.2, py-1.8.0, pluggy-0.12.0 -- /home/gino/.virtualenvs/test-py37/bin/python3.7
cachedir: .pytest_cache
rootdir: /home/gino/Project, inifile: pytest.ini, testpaths: tests
collected 1 item
tests/test_one.py::test_calculate PASSED [1/1]
============================================================================ 1 passed in 0.01 seconds =============================================================================