1

I am using the @pytest.mark.parametrizefunctionality to test multiple test cases using pytest. Now I am having a hard time understanding how do I test if my function throws a KeyError by default, how do I write a test for it?

In the example below, transcript and category are the two input parameter. category is the key.

@pytest.mark.parametrize("transcript, category, category_naming_score", [
    ("orange banana apple", "fruits", 3),
    ("carrot celery spinach", "vegetables", 3),
    ("birds cardinals blackbirds crows", "birds", 3),
    ("", "fruits", 0),
    ("cardinals", "", pytest.raises(KeyError))])
def test_category_naming_calculate_score(transcript, category, category_naming_score):
    assert calculate_score(transcript, category) == category_naming_score

So in the example above the second argument is supposed to be a key to a lookup dictionary, by default the function throws a KeyError if it is unable to find the the key. In the last test case my function will throw an error KeyError: ''. I am not sure how to make sure I am catching that exception as a pytest.

1
  • 2
    Probably best to write a separate test for the case where an exception is expected, otherwise you have to add some awkward workaround. Commented Mar 13, 2020 at 18:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.