Fixtures

One of the great things about pytest is how it facilitates creating reusable features so that we can feed our tests with data or objects in order to test more effectively and without repetition.

For example, we might want to create a MergeRequest object in a particular state, and use that object in multiple tests. We define our object as a fixture by creating a function and applying the @pytest.fixture decorator. The tests that want to use that fixture will have to have a parameter with the same name as the function that's defined, and pytest will make sure that it's provided:

@pytest.fixture
def rejected_mr():
merge_request = MergeRequest()

merge_request.downvote("dev1")
merge_request.upvote("dev2")
merge_request.upvote("dev3")
merge_request.downvote("dev4")

return merge_request

def test_simple_rejected(rejected_mr):
assert rejected_mr.status == MergeRequestStatus.REJECTED

def test_rejected_with_approvals(rejected_mr):
rejected_mr.upvote("dev2")
rejected_mr.upvote("dev3")
assert rejected_mr.status == MergeRequestStatus.REJECTED

def test_rejected_to_pending(rejected_mr):
rejected_mr.upvote("dev1")
assert rejected_mr.status == MergeRequestStatus.PENDING

def test_rejected_to_approved(rejected_mr):
rejected_mr.upvote("dev1")
rejected_mr.upvote("dev2")
assert rejected_mr.status == MergeRequestStatus.APPROVED

Remember that tests affect the main code as well, so the principles of clean code apply to them as well. In this case, the Don't Repeat Yourself (DRY) principle that we explored in previous chapters appears once again, and we can achieve it with the help of pytest fixtures.

Besides creating multiple objects or exposing data that will be used throughout the test suite, it's also possible to use them to set up some conditions, for example, to globally patch some functions that we don't want to be called, or when we want patch objects to be used instead.

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

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