27

我对,和:有一个奇怪的问题tox,当从 启动该选项时,它似乎需要文件夹中的一个文件,这不是立即显而易见的。py.testcoveragepytest-covpy.test--covtox__init__.pytests

在写这篇文章时,我已经通过添加上述内容解决了最初的问题tests/__init__.py,但是到目前为止,我并不完全理解它为什么会起作用或不起作用,所以我仍然在寻求帮助。请参阅下面的详细资料。

我在 SO 上找到了一个相关的问题,但它只会让它更加混乱,因为答案似乎与我到目前为止所想出的相反: `py.test` 和 `__init__.py` 文件

另请参阅此处的官方文档:py.test - 良好的集成实践(页面的最底部)。


简化的项目结构:

setup.py
tox.ini
.coveragerc
project/
    __init__.py
    module1.py
    module2.py
    tests/
        __init__.py (optional, an empty file)
        test_module1.py
        test_module2.py

相关部分tox.ini

[testenv:check]
commands = py.test --cov=project --cov-report=term
deps =
    pytest
    coverage
    pytest-cov

[pytest]
python_files = test_*.py
norecursedirs = .tox

相关部分.coveragerc

[run]
branch = True
omit = project/tests/*

现在,结果:

  • py.test --cov=project --cov-report=termtests/__init__.py无论文件是否存在,从项目根目录运行 => 正确覆盖。
  • tox -e check没有tests/__init__.py=> 测试被发现并运行,但我收到警告“Coverage.py 警告:未收集数据。” 所有模块的覆盖率为 0%
  • tox -e checktests/__init__.py=> 再次正确覆盖。

对我来说,为什么tests/__init__.py文件必须在那里(添加这个空文件解决了最初的问题)以进行tox运行并不是很明显,但是当您手动运行测试/覆盖时并不重要。有任何想法吗?

4

2 回答 2

50

--cov {envsitepackagesdir}/<your-package-name>在 tox.ini 中使用。

于 2014-03-07T17:18:22.187 回答
4

See: Using py.test with coverage doesn't include imports

I got rid of using pytest-cov and run coverage outright instead..

Also noticed with pytest, I did need the blank __init__.py in my test directory to function correctly. There is probably a reason for it somewhere.

I realize this is a couple of years old, but in case someone else comes across this..

于 2016-12-29T21:24:24.950 回答