对名称“max”和“alex”的评估应该是整体true,当且仅当所有三个输入(健康、高大、富有)均为 1。如果至少其中一个输入等于 0,则应为“假”被退回。
但是,似乎始终必须传递第一个条件(在本例中为健康)的输入值,以免出现 KeyError。怎么才能改变呢?
请参阅以下代码片段,在测试 2 中,我收到了 KeyError。相比之下,对于测试 3,我提供了“健康”值,结果符合预期。
import pytest
def function(x: dict) -> str:
try:
if x["name"] in ["max", "alex"]:
if x["healthy"] != 1:
return "false"
if x["tall"] != 1:
return "false"
if x["rich"] != 1:
return "false"
return "true"
except KeyError:
return "input_is_missing"
class TestEvaluate:
false = "false"
true = "true"
input_is_missing = "input_is_missing"
@pytest.mark.parametrize(
"inputs, expected",
[
# Test 1
(
{
"name": "max",
"healthy": 0,
},
false,
),
# Test 2
(
{
"name": "max",
"tall": 0,
},
false,
),
# Test 3
(
{
"name": "max",
"healthy": 1,
"tall": 0,
},
false,
),
],
)
def test_valid_inputs(self, inputs, expected):
assert function(inputs) == expected
要解决在缺少“健康”输入时接收 KeyError 的问题,您可以通过在访问其值之前检查输入字典中是否存在“健康”键来修改代码。这是代码的更新版本:
def function(x: dict) -> str:
try:
if x["name"] in ["max", "alex"]:
# Check if the "healthy" key is present in the input dictionary
if "healthy" not in x:
return "false"
if x["healthy"] != 1:
return "false"
if x["tall"] != 1:
return "false"
if x["rich"] != 1:
return "false"
return "true"
return "false"
except KeyError:
return "input_is_missing"
在此更新的代码中,如果输入字典中缺少“healthy”键,该函数将立即返回“false”,而不检查其他条件。这可确保不会引发 KeyError 并返回正确的输出。
您需要首先检查health、high或rich中的任何一个是否明确设置为0。如果是,则返回false。
排序后,返回值为 true 的唯一情况是所有这些都可用且设置为 1。在这种情况下返回 true。访问这些值时,如果其中任何一个缺失,您将自动得到一个 KeyError ,因此响应 input_is_missing。
def function(x: dict) -> str:
try:
if x["name"] in ["max", "alex"]:
if "healthy" in x and x["healthy"] == 0:
return "false"
if "tall" in x and x["tall"] == 0:
return "false"
if "rich" in x and x["rich"] == 0:
return "false"
if x["healthy"] == 1 and x["tall"] == 1 and x["rich"] == 1:
return "true"
except KeyError:
return "input_is_missing"