3

I'm migrating all my modules to Poetry and I have a problem.

Before with a python setup.py test I was able to run my tests with the correct coverage information.

Now I'm moving to poetry, so my best option is poetry run pytest or otherwise poetry install; pytest. In both cases, I have to specify the source location in Sonar to collect the coverage data. Here I would naturally just pass my src folder, but clearly the references will be wrong because pytest is running using the code installed in the environment by poetry, not on the local code as it used to happen before, so the references will be mismatched. No amount of tinkering seems to be working.

So, is there a way with poetry to use the local references instead of the environment references when running with pytest? Or should I give up and use some weird trick with inspect to retrieve the path of the installed package in the site-packages folder?

4

1 回答 1

1

您当前pytest针对已安装包而不是源文件运行的设置非常可取,因为它模拟了代码在使用中的行为。路径错误、未正确标记/移动以进行安装的文件或任何其他在部署期间可能出错的事情将立即免费遇到。

它还有助于提供更准确的覆盖,因为例如任何不属于包的构建文件都将被忽略。为了告诉你coverage查看包而不是你的源文件,你只需要准确地告诉它。有这个.coveragerc就足够了:

[run]
source = sample_project

给定这样的项目结构[1]

.
├── .coveragerc
├── src
│   └── sample_project
│       ├── __init__.py
│       └── util.py
└── tests
    ├── __init__.py
    └── test_util.py

运行pytest --cov tests/正确地查看已安装包的内部:

Test session starts (platform: linux, Python 3.7.2, pytest 3.10.1, pytest-sugar 0.9.2)
rootdir: /home/user/dev/sample_project, inifile:
plugins: sugar-0.9.2, cov-2.7.1
collecting ... 
 tests/test_util.py ✓                                                  100% ██████████

----------- coverage: platform linux, python 3.7.2-final-0 -----------
Name                 Stmts   Miss  Cover
----------------------------------------
tests/__init__.py        0      0   100%
tests/test_util.py       6      0   100%
----------------------------------------
TOTAL                    6      0   100%


Results (0.10s):
       1 passed

[1]将源代码拆分到目录中以避免名称隐藏可能很重要(导入机制将更喜欢其 PYTHONPATH 中的本地包 foo,其工作目录始终是已安装包 foo 的一部分)。根据您的描述,您似乎已经在这样做了。如果您不是,请考虑再次设置您的项目,启用新的诗歌并启用其可选的 --src 标志。

于 2019-08-07T07:32:01.343 回答