Python pytest传递数据以进行清理

Python pytest传递数据以进行清理,python,pytest,web-api-testing,Python,Pytest,Web Api Testing,我正在为post api编写测试,它返回创建的资源。但是如何将这些数据传递给python中的fixture,以便它在测试完成后能够进行清理呢 清理: @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

我正在为post api编写测试,它返回创建的资源。但是如何将这些数据传递给python中的fixture,以便它在测试完成后能够进行清理呢

清理:

@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)
测试:


将响应(ID)传递回夹具以进行清理的最佳方式是什么。不希望将清理作为测试的一部分。

您可以使用请求实例访问该ID,并通过
request.instance.variableName
使用代码中的任何位置。例如,假设您删除id
delete(resource\u id)
的方法,在这里

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)
def test_post(delete_after_post,request):
    request.node.resourceId='3'
测试文件xyz_test.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)
def test_post(delete_after_post,request):
    request.node.resourceId='3'

我的方法是创建一个名为TestRunContext的类,并设置静态变量来传递数据

文件:test_run_context.py

class TestRunContext:
      id_under_test = 0
文件:conftest.py

@pytest.fixture(scope='function')
def delete_after_post():
    print('hello')

    yield

    url = 'http://127.0.0.1:5000/api/centres/{0}'.format(TestRunContext.id_under_test)
    resp = requests.delete(url)
文件:test_post.py

def test_创建_post(在_post之后删除):
后期数据={
“名称”:“测试”,
“地址1”:“测试”,
‘城市’:‘测试’,
'邮政编码':'测试',
}
url='1〕http://127.0.0.1:5000/api/centres'
data=requests.post(url,post\u数据)
test=data.id下的TestRunContext.id
断言数据


这对我来说暂时有效。但希望找到比使用ContextManager文件更好的解决方案。我真的不喜欢这个解决方案。

我为此创建了一个收集清理功能的装置:

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))

这样,每个用例就不需要单独的夹具。

为什么不使用每个方法设置/拆卸?在安装中保存ID,在拆卸中清除ID。ID是由测试中的API生成的,并且事先不知道。因此请求保存测试运行的上下文。这听起来是一个完成任务的好方法。看起来它似乎无法识别测试中的“请求”
>request.instance.resourceId=3 E AttributeError:“非类型”对象没有属性“resourceId”
我已更新了答案。这在我这边完全行得通。夹具或测试不属于任何类别。夹具位于一个名为conftest.py的文件中,测试位于一个文件test_post.py中,它们都位于一个包(文件夹)test下。您不能将您的测试方法仅绑定到一个类中吗??要使用请求实例,fixture和test的Bcz范围必须相同。这不是最好的答案。Chanda Korat的上述答案是迄今为止更好的答案。