Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest passing data for cleanup

I'm writing tests for a post api, which returns the resource that gets created. But how do I pass this data to a fixture in python so it can cleanup after the test is completed

Cleanup:

@pytest.fixture(scope='function')
def delete_after_post(request):
    def cleanup():
        // Get ID of resource to cleanup
        // Call Delete api with ID to delete the resource
    request.addfinalizer(cleanup)

Test:

 def test_post(delete_after_post):
     Id = post(api)
     assert Id

What is the best way to pass the response(ID) back to to the fixture for the cleanup to kick in. Don't want to do the cleanup as part of the test.

like image 601
Mateen-Hussain Avatar asked Apr 08 '26 02:04

Mateen-Hussain


2 Answers

You can access that ID using request instance and use anywhere in your code by request.instance.variableName. Like, Suppose your method for deleting id delete(resource_id), here

conftest.py

import pytest

@pytest.fixture(scope='function')
def delete_after_post(request):
    def cleanup():
        print request.node.resourceId
        # Get ID of resource using request.instance.resourceId
        # Call Delete api with ID to delete the resource

    request.addfinalizer(cleanup)

test file xyz_test.py

def test_post(delete_after_post,request):
    request.node.resourceId='3'
like image 182
Chanda Korat Avatar answered Apr 09 '26 15:04

Chanda Korat


I created a fixture that collects cleanup functions for this purpose:

import pytest

@pytest.fixture
def cleaner():
    funcs = []
    def add_func(func):
        funcs.append(func)
    yield add_func
    for func in funcs:
        func()

def test_func(cleaner):
    x = 5
    cleaner(lambda: print('cleaning', x))

This way you don't need a separate fixture for each use case.

like image 36
Kris Avatar answered Apr 09 '26 14:04

Kris