0

我正在使用 pytest 覆盖率,然后我在命令行中有测试脚本,将为我生成覆盖率报告:

"""Manager script to run the commands on the Flask API."""
import os
import click
from api import create_app
from briqy.logHelper import b as logger
import pytest

app = create_app()


@app.cli.command("tests")
@click.argument("option", required=False)
def run_test_with_option(option: str = None):
    from subprocess import run
    from shlex import split

    if option is None:
        raise SystemExit(
            pytest.main(
                [
                    "--disable-pytest-warnings",
                    "--cov=lib",
                    "--cov-config=.coveragerc",
                    "--cov-report=term",
                    "--cov-report=xml",
                    "--cov-report=html",
                    "--junitxml=./tests/coverage/junit.xml",
                    "--cov-append",
                    "--no-cov-on-fail",
                ]
            )
        )
    elif option == "watch":
        run(
            split(
                'ptw --runner "python3 -m pytest tests --durations=5 '
                '--disable-pytest-warnings"'
            )
        )
    elif option == "debug":
        run(
            split(
                'ptw --pdb --runner "python3 -m pytest tests --durations=5 '
                '--disable-pytest-warnings"'
            )
        )


if __name__ == "__main__":
    HOST = os.getenv("FLASK_RUN_HOST", default="127.0.0.1")
    PORT = os.getenv("FLASK_RUN_PORT", default=5000)
    DEBUG = os.getenv("FLASK_DEBUG", default=False)

    app.run(
        host=HOST,
        port=PORT,
        debug=DEBUG,
    )

    if bool(DEBUG):
        logger.info(f"Flask server is running in {os.getenv('ENV')}")

但是,在运行测试之后,它会显示测试发现的文件顶部的导入。有谁知道如何摆脱那些未覆盖的线条?

4

2 回答 2

1

你没有展示整个程序,但我猜你是在这个文件的顶部导入你的产品代码。这意味着在 pytest-cov 插件开始覆盖测量时,产品代码中的所有顶级语句(import、class、def 等)都已经运行。

您可以做几件事:

  1. 从命令行而不是在产品代码中运行 pytest。
  2. 更改此代码以在子进程中启动 pytest,以便 pytest 重新导入所有内容。

您不应该做的事情:从覆盖率测量中排除导入行。您显示的 .coveragerc 将忽略其中包含字符串“from”或“import”的任何行,这不是您想要的(例如,“import”在“do_important_thing()”中!)

于 2022-01-13T12:09:29.407 回答
0

我设法通过将以下行添加到我的.coveragerc. 以下是我制作的cahgne .coveragerc

[report]
.
.
.
exclude_lines=
    # Ignore imports
    from
    import


但是,我仍在def func_name(): ...为测试发现的函数定义()而苦苦挣扎。

于 2022-01-12T17:12:26.743 回答