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.

Samarth
  • 242
  • 2
  • 12
  • 2
    Probably best to write a separate test for the case where an exception is expected, otherwise you have to add some awkward workaround. – MrBean Bremen Mar 13 '20 at 18:44

0 Answers0