Assertion checking

To confirm the exception raised by a test, the unittest.TestCase class has methods like assertRaises(). When working with pytest, we have a distinct approach to testing this feature. The pytest package offers a context manager named raises to help detect the exception that is raised. The raises context is shown in this example: 

from pytest import raises

def test_card_factory():

c1 = card(1, Suit.CLUB)
assert isinstance(c1, AceCard)

c2 = card(2, Suit.DIAMOND)
assert isinstance(c1, Card)

c10 = card(10, Suit.HEART)
assert isinstance(c10, Card)

cj = card(11, Suit.SPADE)
assert isinstance(cj, FaceCard)

ck = card(13, Suit.CLUB)
assert isinstance(ck, FaceCard)

with raises(LogicError):
c14 = card(14, Suit.DIAMOND)

with raises(LogicError):
c0 = card(0, Suit.DIAMOND)

We've used pytest.raises as a context manager. When this is provided with a class definition, the statements within the context are expected to raise the named exception. If the exception is raised, the test passes; if the exception is not raised, this is a test failure.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset