为什么在此python-inquirer脚本中覆盖率不是100%?

问题描述 投票:1回答:1

我有一个简单的方法,可以接收交易列表(描述和ID)并返回所选交易的ID。如果未选择任何一项,则要求您确认。我用python-inquirer来做到这一点:

# question.py
from typing import List, Tuple
import inquirer

def select_trades(trades: List[Tuple[str, int]]) -> List[int]:
    while True:
        selection = inquirer.prompt(
            [
                inquirer.Checkbox(
                    "trades",
                    message=(
                        "Select auction trades? "
                        "(press space to select and enter to finish)"
                    ),
                    choices=trades,
                )
            ]
        )["trades"]
        if len(selection) == 0:
            answer = inquirer.prompt(
                [
                    inquirer.List(
                        "",
                        message="No trade selected.\nDo you confirm?",
                        choices=["Yes", "No"],
                    )
                ]
            )[""]
            if answer == "Yes":
                return []
        else:
            break
    return selection

我做了2个测试用例。您选择一个都不选择,不确认,再次选择一个并确认。另一种情况是您选择ID 1:

# test_question.py
from unittest.mock import patch

from question import select_trades

@patch(
    "inquirer.prompt",
    side_effect=[{"trades": []}, {"": "No"}, {"trades": []}, {"": "Yes"}],
)
def test_select_trades_empty(mock_inquirer_prompt) -> None:
    trades = [("trade 1", 0), ("trade 2", 1)]
    assert select_trades(trades) == []


@patch("inquirer.prompt", return_value={"trades": [1]})
def test_select_trades_some_selected(mock_inquirer_prompt) -> None:
    trades = [("trade 1", 0), ("trade 2", 1)]
    assert select_trades(trades) == [1]

[出于某种原因,覆盖范围是说break类没有被覆盖,但是在第二个测试用例中,while True断开并返回测试的期望值。我不明白为什么在这种情况下不能100%覆盖它。

python python-3.x unit-testing command-line-interface coverage.py
1个回答
0
投票

这是由于Python优化了跳转,使得Coverage.py无法看到此行被覆盖(https://github.com/nedbat/coveragepy/issues/198)。

© www.soinside.com 2019 - 2024. All rights reserved.