【问题标题】:Why not getting 100% coverage on FastAPI with pytest-cov using starlettes TestClient为什么不使用 starlettes TestClient 使用 pytest-cov 获得 100% 的 FastAPI 覆盖率
【发布时间】:2020-09-27 15:05:00
【问题描述】:

我只是不明白 pytest-cov 的输出

我的测试模块如下

from starlette.testclient import TestClient


def test_ping(test_app: TestClient):
    response = test_app.get("/ping")
    assert response.status_code == 200
    assert response.json() == {"environment": "dev", "ping": "pong!", "testing": True}

即我不明白 1 部分和 1 缺失。完整的 CLI 报告:

❯ docker-compose exec web coverage report -m                          
Name                     Stmts   Miss Branch BrPart  Cover   Missing
--------------------------------------------------------------------
app/__init__.py              0      0      0      0   100%
app/api/__init__.py          0      0      0      0   100%
app/api/crud.py             14      0      2      0   100%
app/api/ping.py              7      1      2      1    78%   267, 10->9
app/api/summaries.py        20      0      8      5    82%   12->11, 12->19, 19->18, 19->24, 24->23
app/config.py               12      0      2      1    93%   16->15
app/db_init.py               8      1      0      0    88%   268
app/main.py                 19      2      4      3    78%   270-274, 25->24, 25->31, 31->30
app/models/__init__.py       0      0      0      0   100%
app/models/pydantic.py       5      0      0      0   100%
app/models/tortoise.py       9      1      0      0    89%   11
db_generate_schema.py       13     13      2      0     0%   1-274
--------------------------------------------------------------------
TOTAL                      107     18     20     10    76%

首先我想了解缺少的267, 10->9 - 我什至该文件中的行数都不超过 15 行。这可能也可以解释剩下的问题。

【问题讨论】:

  • 我猜部分覆盖是因为你从不使用非默认设置值测试它。
  • 你指的设置?实际上,您实际上不应该在 FastAPI 框架中更改它 - 猜想这是通知 FastAPI 的事情。但失踪真的很奇怪,不是吗?
  • 在测试 fastAPI 应用程序时,我还看到不正确的缺失行。在我的情况下,这些行是真正的代码行,但我的测试正在执行它们。它们都在路由器中,并且都是引发异常的分支(例如,在未找到记录时引发 404)。我不知道如何提高覆盖率报告的准确性。

标签: python fastapi pytest-cov starlette


【解决方案1】:

也许它与我的问题有关

当它错过随机线时

pytest coverage skips some lines

【讨论】:

猜你喜欢
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 2022-06-11
  • 2019-11-06
  • 1970-01-01
  • 2023-02-17
  • 2020-02-26
  • 1970-01-01
相关资源
最近更新 更多