pytest Quick Start Guide
上QQ阅读APP看书,第一时间看更新

Checking exception messages

As stated at the start of this section, APIs should provide clear messages in the exceptions they raise. In the previous examples, we only verified that the code was raising the appropriate exception type, but not the actual message.

pytest.raises can receive an optional match argument, which is a regular expression string that will be matched against the exception message, as well as checking the exception type. For more details, go to: https://docs.python.org/3/howto/regex.html. We can use that to improve our tests even further:

def test_empty_name():
with pytest.raises(InvalidCharacterNameError,
match='character name empty'):
create_character(name='', class_name='warrior')


def test_invalid_class_name():
with pytest.raises(InvalidClassNameError,
match='invalid class name: "mage"'):
create_character(name='Solaire', class_name='mage')

Simple!