这是原代码,可以正常添加附件,allure 报告效果如下:
:
@pytest.fixture(scope="session", autouse=True)
def tf_get_trainerId_xiehe(tf_getSession):
url = Environment.HOST_ADMIN + 'managerList'
data = {'page': 1,
'limit': 30,
'keys': Environment.userphone_tea,
'characterType': 1,
'roles': ''}
resp = tf_getSession.post(url=url, data=data)
"""
初始想法:我定义了许多fixture,有大部分fixture都需要下面的断言并写allure附件的代码,
所以为了复用,我期望是将下面的代码提出来,但提出来之后发现就无法成功写入allure附件了。
"""
allure.step("Check response status code and content")
try:
assert resp.status_code == 200, f"Expected status code 200 but got {resp.status_code}"
assert resp.json()['code'] == 2000, f"Expected code {2000} but got {resp.json()['code']}"
AssociatedDataTanQiang.id_xiehe_admin = resp.json()['data']['list'][0]['id']
except (AssertionError,IndexError) as e:
allure.attach(
json.dumps(resp.json(), ensure_ascii=False, indent=2),
name="response.json",
attachment_type=allure.attachment_type.JSON
)
allure.attach(
resp.text,
name="response.text",
attachment_type=allure.attachment_type.TEXT
)
raise AssertionError(f"Fixture: {tf_get_trainerId_xiehe.__name__}断言失败") from e
yield
这是修改后的代码,无法正常在 allure 报告中添加附件:
def check_response(resp, target_position, expected_code=2000):
allure.step("Check response status code and content")
try:
assert resp.status_code == 200, f"Expected status code 200 but got {resp.status_code}"
assert resp.json()['code'] == expected_code, f"Expected code {expected_code} but got {resp.json()['code']}"
return target_position
except (AssertionError,IndexError) as e:
allure.attach(
json.dumps(resp.json(), ensure_ascii=False, indent=2),
name="response.json",
attachment_type=allure.attachment_type.JSON
)
allure.attach(
resp.text,
name="response.text",
attachment_type=allure.attachment_type.TEXT
)
raise AssertionError(f"Fixture: 断言失败") from e
@pytest.fixture(scope="session", autouse=True)
def tf_get_trainerId_xiehe(tf_getSession):
url = Environment.HOST_ADMIN + 'managerList'
data = {'page': 1,
'limit': 30,
'keys': Environment.userphone_tea,
'characterType': 1,
'roles': ''}
resp = tf_getSession.post(url=url, data=data)
AssociatedDataTanQiang.id_xiehe_admin = check_response(resp,resp.json()['data']['list'][0]['id'])
yield