Basic test cases with pytest

The conditions we tested in the previous section can be rewritten in simple functions with pytest.

Some examples with simple assertions are as follows:

def test_simple_rejected():
merge_request = MergeRequest()
merge_request.downvote("maintainer")
assert merge_request.status == MergeRequestStatus.REJECTED

def test_just_created_is_pending():
assert MergeRequest().status == MergeRequestStatus.PENDING

def test_pending_awaiting_review():
merge_request = MergeRequest()
merge_request.upvote("core-dev")
assert merge_request.status == MergeRequestStatus.PENDING

Boolean equality comparisons don't require more than a simple assert statement, whereas other kinds of checks like the ones for the exceptions do require that we use some functions:

def test_invalid_types():
merge_request = MergeRequest()
pytest.raises(TypeError, merge_request.upvote, {"invalid-object"})

def test_cannot_vote_on_closed_merge_request():
merge_request = MergeRequest()
merge_request.close()
pytest.raises(MergeRequestException, merge_request.upvote, "dev1")
with pytest.raises(
MergeRequestException,
match="can't vote on a closed merge request",
):
merge_request.downvote("dev1")

In this case, pytest.raises is the equivalent of unittest.TestCase.assertRaises, and it also accepts that it be called both as a method and as a context manager. If we want to check the message of the exception, instead of a different method (like assertRaisesRegex), the same function has to be used, but as a context manager, and by providing the match parameter with the expression we would like to identify.

pytest will also wrap the original exception into a custom one that can be expected (by checking some of its attributes such as .value, for instance) in case we want to check for more conditions, but this use of the function covers the vast majority of cases.

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

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