2017-06-23 202 views
0

我正在爲後api編寫測試,它會返回創建的資源。但我怎麼這個數據傳遞給固定在python因此它可以清除測試完成後pytest傳遞數據進行清理

清理:

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

測試:

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

什麼是傳遞的最佳方式將回應(ID)返回給夾具以進行清理。不想將清理作爲測試的一部分。

+0

爲什麼不使用per-method setup/teardown?將ID保存在安裝和清除中。 – phd

+0

ID是由測試中的API生成的,並且事先不知道。 –

回答

0

您可以使用請求實例訪問該ID並在代碼中的任何位置使用request.instance.variableName。就像,假設你的方法刪除ID delete(resource_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) 

測試文件xyz_test.py

def test_post(delete_after_post,request): 
    request.node.resourceId='3' 
+0

因此請求包含測試運行的上下文。這聽起來是完成任務的一個體面的方式。 –

+0

不是。看起來好像它似乎不能識別測試中的「請求」 '> request.instance.resourceId = 3 E AttributeError:'NoneType'對象沒有屬性'resourceId'' –

+0

我已經更新了答案。在我的最後,這完全正常。 –

0

我做的方法是創建一個名爲類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_creates_post(delete_after_post): post_data ={ 'name' : 'test', 'address1': 'test', 'city': 'test', 'postcode': 'test', } url = 'http://127.0.0.1:5000/api/centres' data = requests.post(url, post_data) TestRunContext.id_under_test = data.id assert data

這對我的作品現在。但希望找到比使用ContextManager文件更好的解決方案。真的不喜歡這個解決方案。

+0

這不是最好的答案。 Chanda Korat的上述答案是迄今爲止最好的答案。 –