Assessment for the names "max" and "alex" should be overall true, iff all three inputs (healthy, tall, rich) are 1. If at least one of the inputs is equal to 0, then "false" should be returned.
However, it seems that a value for the input of the first condition (in this case healthy) always has to be passed in order not to get the KeyError. How can that be changed?
See in the following code snippet that for test 2 I get a KeyError. In comparison, for test 3 I provide a value for "healthy" and the result is as expected.
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
To address the issue of receiving a KeyError when the "healthy" input is missing, you can modify the code by checking for the presence of the "healthy" key in the input dictionary before accessing its value. Here's an updated version of the code:
In this updated code, if the "healthy" key is missing from the input dictionary, the function immediately returns "false" without checking the other conditions. This ensures that a KeyError is not raised and that the proper output is returned.